mirror of
https://github.com/Laxilef/OTGateway.git
synced 2026-11-23 14:53:07 +05:00
refactor: migrate ESP32 firmware to task-managed services
Split the header-based firmware into services for OpenTherm, heating control, sensors, networking, logging, and the portal. Run these services with MycilaTaskManager and use ESP32OT for the boiler bus. Move MQTT and Home Assistant discovery to Mycila libraries, expose native crash metrics, and align the board profiles and build hooks with the new dependencies.
This commit is contained in:
1 parent
b10d91b8fa
commit
3fb433d3eb
48 files changed
+14464
-12650
No files matched your search
@@ -1,82 +0,0 @@
|
||||
class BufferedWebServer {
|
||||
public:
|
||||
explicit BufferedWebServer(WebServer* webServer, size_t bufferSize = 64) {
|
||||
this->webServer = webServer;
|
||||
this->bufferSize = bufferSize;
|
||||
this->buffer = static_cast<uint8_t*>(malloc(bufferSize * sizeof(*this->buffer)));
|
||||
}
|
||||
|
||||
~BufferedWebServer() {
|
||||
free(this->buffer);
|
||||
}
|
||||
|
||||
template <class T>
|
||||
void send(int code, T contentType, const JsonVariantConst content, bool pretty = false) {
|
||||
auto contentLength = pretty ? measureJsonPretty(content) : measureJson(content);
|
||||
|
||||
this->webServer->setContentLength(contentLength);
|
||||
this->webServer->send(code, contentType, emptyString);
|
||||
|
||||
if (pretty) {
|
||||
serializeJsonPretty(content, *this);
|
||||
|
||||
} else {
|
||||
serializeJson(content, *this);
|
||||
}
|
||||
|
||||
this->flush();
|
||||
|
||||
this->webServer->sendContent(emptyString);
|
||||
}
|
||||
|
||||
size_t write(uint8_t c) {
|
||||
this->buffer[this->bufferPos++] = c;
|
||||
|
||||
if (this->bufferPos >= this->bufferSize) {
|
||||
this->flush();
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
size_t write(const uint8_t* buffer, size_t length) {
|
||||
size_t written = 0;
|
||||
while (written < length) {
|
||||
size_t copySize = this->bufferSize - this->bufferPos;
|
||||
if (written + copySize > length) {
|
||||
copySize = length - written;
|
||||
}
|
||||
|
||||
memcpy(this->buffer + this->bufferPos, buffer + written, copySize);
|
||||
this->bufferPos += copySize;
|
||||
|
||||
if (this->bufferPos >= this->bufferSize) {
|
||||
this->flush();
|
||||
}
|
||||
|
||||
written += copySize;
|
||||
}
|
||||
|
||||
return written;
|
||||
}
|
||||
|
||||
void flush() {
|
||||
if (this->bufferPos == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto& client = this->webServer->client();
|
||||
if (client.connected()) {
|
||||
this->webServer->sendContent((const char*)this->buffer, this->bufferPos);
|
||||
}
|
||||
|
||||
this->bufferPos = 0;
|
||||
|
||||
}
|
||||
|
||||
protected:
|
||||
WebServer* webServer = nullptr;
|
||||
uint8_t* buffer;
|
||||
size_t bufferSize = 64;
|
||||
size_t bufferPos = 0;
|
||||
};
|
||||
@@ -1,195 +0,0 @@
|
||||
#include <Arduino.h>
|
||||
#include <OpenTherm.h>
|
||||
|
||||
class CustomOpenTherm : public OpenTherm {
|
||||
public:
|
||||
typedef std::function<void(unsigned int)> DelayCallback;
|
||||
typedef std::function<void(unsigned long, uint8_t)> BeforeSendRequestCallback;
|
||||
typedef std::function<void(unsigned long, unsigned long, OpenThermResponseStatus, uint8_t)> AfterSendRequestCallback;
|
||||
|
||||
explicit CustomOpenTherm(int inPin = 4, int outPin = 5, bool isSlave = false, bool alwaysReceive = false) : OpenTherm(inPin, outPin, isSlave, alwaysReceive) {}
|
||||
~CustomOpenTherm() {}
|
||||
|
||||
CustomOpenTherm* setDelayCallback(DelayCallback callback = nullptr) {
|
||||
this->delayCallback = callback;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
CustomOpenTherm* setBeforeSendRequestCallback(BeforeSendRequestCallback callback = nullptr) {
|
||||
this->beforeSendRequestCallback = callback;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
CustomOpenTherm* setAfterSendRequestCallback(AfterSendRequestCallback callback = nullptr) {
|
||||
this->afterSendRequestCallback = callback;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
unsigned long sendRequest(unsigned long request) override {
|
||||
this->sendRequestAttempt++;
|
||||
|
||||
while (!this->isReady()) {
|
||||
if (this->delayCallback) {
|
||||
this->delayCallback(150);
|
||||
}
|
||||
|
||||
this->process();
|
||||
}
|
||||
|
||||
if (this->beforeSendRequestCallback) {
|
||||
this->beforeSendRequestCallback(request, this->sendRequestAttempt);
|
||||
}
|
||||
|
||||
if (this->sendRequestAsync(request)) {
|
||||
do {
|
||||
if (this->delayCallback) {
|
||||
this->delayCallback(150);
|
||||
}
|
||||
|
||||
this->process();
|
||||
} while (this->status != OpenThermStatus::READY && this->status != OpenThermStatus::DELAY);
|
||||
}
|
||||
|
||||
if (this->afterSendRequestCallback) {
|
||||
this->afterSendRequestCallback(request, this->response, this->responseStatus, this->sendRequestAttempt);
|
||||
}
|
||||
|
||||
if (this->responseStatus == OpenThermResponseStatus::SUCCESS || this->responseStatus == OpenThermResponseStatus::INVALID) {
|
||||
this->sendRequestAttempt = 0;
|
||||
return this->response;
|
||||
|
||||
} else if (this->sendRequestAttempt >= this->sendRequestMaxAttempts) {
|
||||
this->sendRequestAttempt = 0;
|
||||
return this->response;
|
||||
|
||||
} else {
|
||||
return this->sendRequest(request);
|
||||
}
|
||||
}
|
||||
|
||||
inline auto sendBoilerReset() {
|
||||
return this->sendRequestCode(1);
|
||||
}
|
||||
|
||||
inline auto sendServiceReset() {
|
||||
return this->sendRequestCode(10);
|
||||
}
|
||||
|
||||
inline auto sendWaterFilling() {
|
||||
return this->sendRequestCode(2);
|
||||
}
|
||||
|
||||
bool sendRequestCode(const uint8_t requestCode) {
|
||||
unsigned long response = this->sendRequest(buildRequest(
|
||||
OpenThermMessageType::WRITE_DATA,
|
||||
OpenThermMessageID::RemoteRequest,
|
||||
static_cast<unsigned int>(requestCode) << 8
|
||||
));
|
||||
|
||||
if (!isValidResponse(response) || !isValidResponseId(response, OpenThermMessageID::RemoteRequest)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const uint8_t responseRequestCode = (response & 0xFFFF) >> 8;
|
||||
const uint8_t responseCode = response & 0xFF;
|
||||
if (responseRequestCode != requestCode || responseCode < 128) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// reset
|
||||
this->sendRequest(buildRequest(
|
||||
OpenThermMessageType::WRITE_DATA,
|
||||
OpenThermMessageID::RemoteRequest,
|
||||
0u << 8
|
||||
));
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool getStr(OpenThermMessageID id, char* buffer, uint16_t length = 50) {
|
||||
if (buffer == nullptr || length == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
unsigned long response;
|
||||
uint8_t index = 0;
|
||||
uint8_t maxIndex = 255;
|
||||
|
||||
while (index <= maxIndex && index < length) {
|
||||
response = this->sendRequest(buildRequest(
|
||||
OpenThermMessageType::READ_DATA,
|
||||
id,
|
||||
static_cast<unsigned int>(index) << 8
|
||||
));
|
||||
|
||||
if (!isValidResponse(response) || !isValidResponseId(response, id)) {
|
||||
break;
|
||||
}
|
||||
|
||||
const uint8_t character = response & 0xFF;
|
||||
if (character == 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (index == 0) {
|
||||
maxIndex = (response & 0xFFFF) >> 8;
|
||||
}
|
||||
|
||||
buffer[index++] = static_cast<char>(character);
|
||||
}
|
||||
|
||||
buffer[index] = '\0';
|
||||
return index > 0;
|
||||
}
|
||||
|
||||
static bool isCh2Active(unsigned long response) {
|
||||
return response & 0x20;
|
||||
}
|
||||
|
||||
static bool isValidResponseId(unsigned long response, OpenThermMessageID id) {
|
||||
const uint8_t responseId = (response >> 16) & 0xFF;
|
||||
|
||||
return static_cast<uint8_t>(id) == responseId;
|
||||
}
|
||||
|
||||
static uint8_t getResponseMessageTypeId(unsigned long response) {
|
||||
return (response << 1) >> 29;
|
||||
}
|
||||
|
||||
static const char* getResponseMessageTypeString(unsigned long response) {
|
||||
uint8_t msgType = getResponseMessageTypeId(response);
|
||||
|
||||
switch (msgType) {
|
||||
case static_cast<uint8_t>(OpenThermMessageType::READ_ACK):
|
||||
case static_cast<uint8_t>(OpenThermMessageType::WRITE_ACK):
|
||||
case static_cast<uint8_t>(OpenThermMessageType::DATA_INVALID):
|
||||
case static_cast<uint8_t>(OpenThermMessageType::UNKNOWN_DATA_ID):
|
||||
return CustomOpenTherm::messageTypeToString(
|
||||
static_cast<OpenThermMessageType>(msgType)
|
||||
);
|
||||
|
||||
default:
|
||||
return "UNKNOWN";
|
||||
}
|
||||
}
|
||||
|
||||
// converters
|
||||
template <class T>
|
||||
static unsigned int toFloat(const T val) {
|
||||
return (unsigned int)(val * 256);
|
||||
}
|
||||
|
||||
static short getInt(const unsigned long response) {
|
||||
return response & 0xffff;
|
||||
}
|
||||
|
||||
protected:
|
||||
const uint8_t sendRequestMaxAttempts = 5;
|
||||
uint8_t sendRequestAttempt = 0;
|
||||
DelayCallback delayCallback;
|
||||
BeforeSendRequestCallback beforeSendRequestCallback;
|
||||
AfterSendRequestCallback afterSendRequestCallback;
|
||||
};
|
||||
@@ -1,180 +0,0 @@
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
#include "strings.h"
|
||||
|
||||
class HomeAssistantHelper {
|
||||
public:
|
||||
typedef std::function<void(const char*, bool)> PublishEventCallback;
|
||||
|
||||
HomeAssistantHelper() = default;
|
||||
|
||||
void setWriter() {
|
||||
this->writer = nullptr;
|
||||
}
|
||||
|
||||
void setWriter(MqttWriter* writer) {
|
||||
this->writer = writer;
|
||||
}
|
||||
|
||||
void setPublishEventCallback(PublishEventCallback callback) {
|
||||
this->publishEventCallback = callback;
|
||||
}
|
||||
|
||||
void setDevicePrefix(const char* value) {
|
||||
this->devicePrefix = value;
|
||||
}
|
||||
|
||||
void setDeviceVersion(const char* value) {
|
||||
this->deviceVersion = value;
|
||||
}
|
||||
|
||||
void setDeviceManufacturer(const char* value) {
|
||||
this->deviceManufacturer = value;
|
||||
}
|
||||
|
||||
void setDeviceModel(const char* value) {
|
||||
this->deviceModel = value;
|
||||
}
|
||||
|
||||
void setDeviceName(const char* value) {
|
||||
this->deviceName = value;
|
||||
}
|
||||
|
||||
void setDeviceConfigUrl(const char* value) {
|
||||
this->deviceConfigUrl = value;
|
||||
}
|
||||
|
||||
bool publish(const char* topic, JsonDocument& doc) {
|
||||
if (this->writer == nullptr) {
|
||||
if (this->publishEventCallback) {
|
||||
this->publishEventCallback(topic, false);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
doc[HA_DEVICE][HA_IDENTIFIERS][0] = this->devicePrefix;
|
||||
doc[HA_DEVICE][HA_SW_VERSION] = this->deviceVersion;
|
||||
|
||||
if (this->deviceManufacturer != nullptr) {
|
||||
doc[HA_DEVICE][HA_MANUFACTURER] = this->deviceManufacturer;
|
||||
}
|
||||
|
||||
if (this->deviceModel != nullptr) {
|
||||
doc[HA_DEVICE][HA_MODEL] = this->deviceModel;
|
||||
}
|
||||
|
||||
if (this->deviceName != nullptr) {
|
||||
doc[HA_DEVICE][HA_NAME] = this->deviceName;
|
||||
}
|
||||
|
||||
if (this->deviceConfigUrl != nullptr) {
|
||||
doc[HA_DEVICE][HA_CONF_URL] = this->deviceConfigUrl;
|
||||
}
|
||||
|
||||
bool result = this->writer->publish(topic, doc, true);
|
||||
doc.clear();
|
||||
doc.shrinkToFit();
|
||||
|
||||
if (this->publishEventCallback) {
|
||||
this->publishEventCallback(topic, result);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
bool publish(const char* topic) {
|
||||
if (this->writer == nullptr) {
|
||||
if (this->publishEventCallback) {
|
||||
this->publishEventCallback(topic, false);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool result = writer->publish(topic, nullptr, 0, true);
|
||||
if (this->publishEventCallback) {
|
||||
this->publishEventCallback(topic, result);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
template <class CT, class NT>
|
||||
String makeConfigTopic(CT category, NT name, char nameSeparator = '/') {
|
||||
String topic = "";
|
||||
topic.concat(this->prefix);
|
||||
topic.concat('/');
|
||||
topic.concat(category);
|
||||
topic.concat('/');
|
||||
topic.concat(this->devicePrefix);
|
||||
topic.concat(nameSeparator);
|
||||
topic.concat(name);
|
||||
topic.concat("/config");
|
||||
return topic;
|
||||
}
|
||||
|
||||
template <class T>
|
||||
String getDeviceTopic(T value, char dpvSeparator = '/') {
|
||||
String topic = "";
|
||||
topic.concat(this->devicePrefix);
|
||||
topic.concat(dpvSeparator);
|
||||
topic.concat(value);
|
||||
return topic;
|
||||
}
|
||||
|
||||
template <class CT, class NT>
|
||||
String getDeviceTopic(CT category, NT name, char dpcSeparator = '/', char cnSeparator = '/') {
|
||||
String topic = "";
|
||||
topic.concat(this->devicePrefix);
|
||||
topic.concat(dpcSeparator);
|
||||
topic.concat(category);
|
||||
topic.concat(cnSeparator);
|
||||
topic.concat(name);
|
||||
return topic;
|
||||
}
|
||||
|
||||
template <class CT, class NT, class ST>
|
||||
String getDeviceTopic(CT category, NT name, ST suffix, char dpcSeparator = '/', char cnSeparator = '/', char nsSeparator = '/') {
|
||||
String topic = "";
|
||||
topic.concat(this->devicePrefix);
|
||||
topic.concat(dpcSeparator);
|
||||
topic.concat(category);
|
||||
topic.concat(cnSeparator);
|
||||
topic.concat(name);
|
||||
topic.concat(nsSeparator);
|
||||
topic.concat(suffix);
|
||||
return topic;
|
||||
}
|
||||
|
||||
template <class DT, class VT>
|
||||
String getEntityIdWithPrefix(DT domain, VT value, char separator = '_') {
|
||||
String topic = "";
|
||||
topic.concat(domain);
|
||||
topic.concat('.');
|
||||
topic.concat(this->devicePrefix);
|
||||
topic.concat(separator);
|
||||
topic.concat(value);
|
||||
return topic;
|
||||
}
|
||||
|
||||
template <class T>
|
||||
String getUniqueIdWithPrefix(T value, char separator = '_') {
|
||||
String topic = "";
|
||||
topic.concat(this->devicePrefix);
|
||||
topic.concat(separator);
|
||||
topic.concat(value);
|
||||
return topic;
|
||||
}
|
||||
|
||||
protected:
|
||||
PublishEventCallback publishEventCallback;
|
||||
MqttWriter* writer = nullptr;
|
||||
const char* prefix = "homeassistant";
|
||||
const char* devicePrefix = "";
|
||||
const char* deviceVersion = "1.0";
|
||||
const char* deviceManufacturer = nullptr;
|
||||
const char* deviceModel = nullptr;
|
||||
const char* deviceName = nullptr;
|
||||
const char* deviceConfigUrl = nullptr;
|
||||
};
|
||||
@@ -1,75 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
const char HA_ENTITY_BINARY_SENSOR[] = "binary_sensor";
|
||||
const char HA_ENTITY_BUTTON[] = "button";
|
||||
const char HA_ENTITY_FAN[] = "fan";
|
||||
const char HA_ENTITY_CLIMATE[] = "climate";
|
||||
const char HA_ENTITY_NUMBER[] = "number";
|
||||
const char HA_ENTITY_SELECT[] = "select";
|
||||
const char HA_ENTITY_SENSOR[] = "sensor";
|
||||
const char HA_ENTITY_SWITCH[] = "switch";
|
||||
|
||||
// https://www.home-assistant.io/integrations/mqtt/#supported-abbreviations-in-mqtt-discovery-messages
|
||||
const char HA_DEFAULT_ENTITY_ID[] = "def_ent_id"; // "default_entity_id "
|
||||
const char HA_DEVICE[] = "dev"; // "device"
|
||||
const char HA_IDENTIFIERS[] = "ids"; // "identifiers"
|
||||
const char HA_SW_VERSION[] = "sw"; // "sw_version"
|
||||
const char HA_MANUFACTURER[] = "mf"; // "manufacturer"
|
||||
const char HA_MODEL[] = "mdl"; // "model"
|
||||
const char HA_NAME[] = "name";
|
||||
const char HA_CONF_URL[] = "cu"; // "configuration_url"
|
||||
const char HA_COMMAND_TOPIC[] = "cmd_t"; // "command_topic"
|
||||
const char HA_COMMAND_TEMPLATE[] = "cmd_tpl"; // "command_template"
|
||||
const char HA_ENABLED_BY_DEFAULT[] = "en"; // "enabled_by_default"
|
||||
const char HA_UNIQUE_ID[] = "uniq_id"; // "unique_id"
|
||||
const char HA_ENTITY_CATEGORY[] = "ent_cat"; // "entity_category"
|
||||
const char HA_ENTITY_CATEGORY_DIAGNOSTIC[] = "diagnostic";
|
||||
const char HA_ENTITY_CATEGORY_CONFIG[] = "config";
|
||||
const char HA_STATE_TOPIC[] = "stat_t"; // "state_topic"
|
||||
const char HA_VALUE_TEMPLATE[] = "val_tpl"; // "value_template"
|
||||
const char HA_OPTIONS[] = "ops"; // "options"
|
||||
const char HA_AVAILABILITY[] = "avty"; // "availability"
|
||||
const char HA_AVAILABILITY_MODE[] = "avty_mode"; // "availability_mode"
|
||||
const char HA_TOPIC[] = "t"; // "topic"
|
||||
const char HA_DEVICE_CLASS[] = "dev_cla"; // "device_class"
|
||||
const char HA_UNIT_OF_MEASUREMENT[] = "unit_of_meas"; // "unit_of_measurement"
|
||||
const char HA_UNIT_OF_MEASUREMENT_C[] = "°C";
|
||||
const char HA_UNIT_OF_MEASUREMENT_F[] = "°F";
|
||||
const char HA_UNIT_OF_MEASUREMENT_PERCENT[] = "%";
|
||||
const char HA_UNIT_OF_MEASUREMENT_L_MIN[] = "L/min";
|
||||
const char HA_UNIT_OF_MEASUREMENT_GAL_MIN[] = "gal/min";
|
||||
const char HA_ICON[] = "ic"; // "icon"
|
||||
const char HA_MIN[] = "min";
|
||||
const char HA_MAX[] = "max";
|
||||
const char HA_STEP[] = "step";
|
||||
const char HA_MODE[] = "mode";
|
||||
const char HA_MODE_BOX[] = "box";
|
||||
const char HA_STATE_ON[] = "stat_on"; // "state_on"
|
||||
const char HA_STATE_OFF[] = "stat_off"; // "state_off"
|
||||
const char HA_PAYLOAD_ON[] = "pl_on"; // "payload_on"
|
||||
const char HA_PAYLOAD_OFF[] = "pl_off"; // "payload_off"
|
||||
const char HA_STATE_CLASS[] = "stat_cla"; // "state_class"
|
||||
const char HA_STATE_CLASS_MEASUREMENT[] = "measurement";
|
||||
const char HA_EXPIRE_AFTER[] = "exp_aft"; // "expire_after"
|
||||
const char HA_CURRENT_TEMPERATURE_TOPIC[] = "curr_temp_t"; // "current_temperature_topic"
|
||||
const char HA_CURRENT_TEMPERATURE_TEMPLATE[] = "curr_temp_tpl"; // "current_temperature_template"
|
||||
const char HA_TEMPERATURE_COMMAND_TOPIC[] = "temp_cmd_t"; // "temperature_command_topic"
|
||||
const char HA_TEMPERATURE_COMMAND_TEMPLATE[] = "temp_cmd_tpl"; // "temperature_command_template"
|
||||
const char HA_TEMPERATURE_STATE_TOPIC[] = "temp_stat_t"; // "temperature_state_topic"
|
||||
const char HA_TEMPERATURE_STATE_TEMPLATE[] = "temp_stat_tpl"; // "temperature_state_template"
|
||||
const char HA_TEMPERATURE_UNIT[] = "temp_unit"; // "temperature_unit"
|
||||
const char HA_MODE_COMMAND_TOPIC[] = "mode_cmd_t"; // "mode_command_topic"
|
||||
const char HA_MODE_COMMAND_TEMPLATE[] = "mode_cmd_tpl"; // "mode_command_template"
|
||||
const char HA_MODE_STATE_TOPIC[] = "mode_stat_t"; // "mode_state_topic"
|
||||
const char HA_MODE_STATE_TEMPLATE[] = "mode_stat_tpl"; // "mode_state_template"
|
||||
const char HA_MODES[] = "modes";
|
||||
const char HA_ACTION_TOPIC[] = "act_t"; // "action_topic"
|
||||
const char HA_ACTION_TEMPLATE[] = "act_tpl"; // "action_template"
|
||||
const char HA_MIN_TEMP[] = "min_temp";
|
||||
const char HA_MAX_TEMP[] = "max_temp";
|
||||
const char HA_TEMP_STEP[] = "temp_step";
|
||||
const char HA_PRESET_MODE_COMMAND_TOPIC[] = "pr_mode_cmd_t"; // "preset_mode_command_topic"
|
||||
const char HA_PRESET_MODE_COMMAND_TEMPLATE[] = "pr_mode_cmd_tpl"; // "preset_mode_command_template"
|
||||
const char HA_PRESET_MODE_STATE_TOPIC[] = "pr_mode_stat_t"; // "preset_mode_state_topic"
|
||||
const char HA_PRESET_MODE_VALUE_TEMPLATE[] = "pr_mode_val_tpl"; // "preset_mode_value_template"
|
||||
const char HA_PRESET_MODES[] = "pr_modes"; // "preset_modes"
|
||||
@@ -1,204 +0,0 @@
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
#include <MqttClient.h>
|
||||
#include <mutex>
|
||||
|
||||
|
||||
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;
|
||||
|
||||
explicit MqttWriter(MqttClient* client, size_t bufferSize = 64) {
|
||||
this->client = client;
|
||||
this->bufferSize = bufferSize;
|
||||
this->buffer = static_cast<uint8_t*>(malloc(bufferSize * sizeof(*this->buffer)));
|
||||
|
||||
this->mutex = new std::mutex();
|
||||
}
|
||||
|
||||
~MqttWriter() {
|
||||
free(this->buffer);
|
||||
|
||||
delete this->mutex;
|
||||
}
|
||||
|
||||
MqttWriter* setYieldCallback(YieldCallback callback = nullptr) {
|
||||
this->yieldCallback = callback;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
MqttWriter* setPublishEventCallback(PublishEventCallback callback) {
|
||||
this->publishEventCallback = callback;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
MqttWriter* setFlushEventCallback(FlushEventCallback callback) {
|
||||
this->flushEventCallback = callback;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
bool lock() {
|
||||
if (!this->mutex->try_lock()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this->locked = true;
|
||||
this->writeAfterLock = 0;
|
||||
this->lockedTime = millis();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool isLocked() {
|
||||
return this->locked;
|
||||
}
|
||||
|
||||
void unlock() {
|
||||
this->locked = false;
|
||||
this->mutex->unlock();
|
||||
}
|
||||
|
||||
bool publish(const char* topic, const JsonVariantConst doc, bool retained = false) {
|
||||
if (!this->client->connected()) {
|
||||
this->bufferPos = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
while (!this->lock()) {
|
||||
if (this->yieldCallback) {
|
||||
this->yieldCallback();
|
||||
}
|
||||
}
|
||||
|
||||
this->bufferPos = 0;
|
||||
size_t docSize = measureJson(doc);
|
||||
size_t written = 0;
|
||||
if (this->client->beginMessage(topic, docSize, retained)) {
|
||||
serializeJson(doc, *this);
|
||||
this->flush();
|
||||
this->client->endMessage();
|
||||
|
||||
written = this->writeAfterLock;
|
||||
}
|
||||
this->unlock();
|
||||
|
||||
if (this->publishEventCallback) {
|
||||
this->publishEventCallback(topic, written, docSize, written == docSize);
|
||||
}
|
||||
|
||||
return written == docSize;
|
||||
}
|
||||
|
||||
bool publish(const char* topic, const char* buffer, bool retained = false) {
|
||||
return this->publish(topic, (const uint8_t*) buffer, strlen(buffer), retained);
|
||||
}
|
||||
|
||||
bool publish(const char* topic, const uint8_t* buffer, size_t length, bool retained = false) {
|
||||
if (!this->client->connected()) {
|
||||
this->bufferPos = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
while (!this->lock()) {
|
||||
if (this->yieldCallback) {
|
||||
this->yieldCallback();
|
||||
}
|
||||
}
|
||||
|
||||
this->bufferPos = 0;
|
||||
size_t written = 0;
|
||||
bool result = false;
|
||||
if (!length || buffer == nullptr) {
|
||||
result = this->client->beginMessage(topic, retained) && this->client->endMessage();
|
||||
|
||||
} else if (this->client->beginMessage(topic, length, retained)) {
|
||||
this->write(buffer, length);
|
||||
this->flush();
|
||||
this->client->endMessage();
|
||||
|
||||
written = this->writeAfterLock;
|
||||
result = written == length;
|
||||
}
|
||||
this->unlock();
|
||||
|
||||
if (this->publishEventCallback) {
|
||||
this->publishEventCallback(topic, written, length, result);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
size_t write(uint8_t c) {
|
||||
this->buffer[this->bufferPos++] = c;
|
||||
|
||||
if (this->bufferPos >= this->bufferSize) {
|
||||
this->flush();
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
size_t write(const uint8_t* buffer, size_t length) {
|
||||
size_t written = 0;
|
||||
while (written < length) {
|
||||
size_t copySize = this->bufferSize - this->bufferPos;
|
||||
if (written + copySize > length) {
|
||||
copySize = length - written;
|
||||
}
|
||||
|
||||
memcpy(this->buffer + this->bufferPos, buffer + written, copySize);
|
||||
this->bufferPos += copySize;
|
||||
|
||||
if (this->bufferPos >= this->bufferSize) {
|
||||
this->flush();
|
||||
}
|
||||
|
||||
written += copySize;
|
||||
}
|
||||
|
||||
return written;
|
||||
}
|
||||
|
||||
bool flush() {
|
||||
if (this->bufferPos == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!this->client->connected()) {
|
||||
this->bufferPos = 0;
|
||||
}
|
||||
|
||||
size_t length = this->bufferPos;
|
||||
size_t written = this->client->write(this->buffer, length);
|
||||
this->client->flush();
|
||||
this->bufferPos = 0;
|
||||
|
||||
if (this->isLocked()) {
|
||||
this->writeAfterLock += written;
|
||||
}
|
||||
|
||||
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;
|
||||
size_t bufferPos = 0;
|
||||
bool locked = false;
|
||||
mutable std::mutex* mutex;
|
||||
unsigned long lockedTime = 0;
|
||||
size_t writeAfterLock = 0;
|
||||
};
|
||||
@@ -1,85 +0,0 @@
|
||||
#include "NetworkConnection.h"
|
||||
using namespace NetworkUtils;
|
||||
|
||||
void NetworkConnection::setup(bool useDhcp) {
|
||||
setUseDhcp(useDhcp);
|
||||
|
||||
WiFi.onEvent(NetworkConnection::onEvent);
|
||||
}
|
||||
|
||||
void NetworkConnection::reset() {
|
||||
status = Status::NONE;
|
||||
rawDisconnectReason = 0;
|
||||
disconnectReason = DisconnectReason::NONE;
|
||||
}
|
||||
|
||||
void NetworkConnection::setUseDhcp(bool value) {
|
||||
useDhcp = value;
|
||||
}
|
||||
|
||||
NetworkConnection::Status NetworkConnection::getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
NetworkConnection::DisconnectReason NetworkConnection::getDisconnectReason() {
|
||||
return disconnectReason;
|
||||
}
|
||||
|
||||
void NetworkConnection::onEvent(WiFiEvent_t event, WiFiEventInfo_t info) {
|
||||
switch (event) {
|
||||
case ARDUINO_EVENT_WIFI_STA_CONNECTED:
|
||||
status = useDhcp ? Status::CONNECTING : Status::CONNECTED;
|
||||
rawDisconnectReason = 0;
|
||||
disconnectReason = DisconnectReason::NONE;
|
||||
break;
|
||||
|
||||
case ARDUINO_EVENT_WIFI_STA_GOT_IP:
|
||||
case ARDUINO_EVENT_WIFI_STA_GOT_IP6:
|
||||
status = Status::CONNECTED;
|
||||
rawDisconnectReason = 0;
|
||||
disconnectReason = DisconnectReason::NONE;
|
||||
break;
|
||||
|
||||
case ARDUINO_EVENT_WIFI_STA_LOST_IP:
|
||||
status = Status::DISCONNECTED;
|
||||
rawDisconnectReason = 0;
|
||||
disconnectReason = DisconnectReason::DHCP_TIMEOUT;
|
||||
break;
|
||||
|
||||
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
|
||||
status = Status::DISCONNECTED;
|
||||
rawDisconnectReason = info.wifi_sta_disconnected.reason;
|
||||
disconnectReason = convertDisconnectReason(info.wifi_sta_disconnected.reason);
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
NetworkConnection::DisconnectReason NetworkConnection::convertDisconnectReason(uint8_t reason) {
|
||||
switch (reason) {
|
||||
case WIFI_REASON_BEACON_TIMEOUT:
|
||||
return DisconnectReason::BEACON_TIMEOUT;
|
||||
|
||||
case WIFI_REASON_NO_AP_FOUND:
|
||||
return DisconnectReason::NO_AP_FOUND;
|
||||
|
||||
case WIFI_REASON_AUTH_FAIL:
|
||||
return DisconnectReason::AUTH_FAIL;
|
||||
|
||||
case WIFI_REASON_ASSOC_FAIL:
|
||||
return DisconnectReason::ASSOC_FAIL;
|
||||
|
||||
case WIFI_REASON_HANDSHAKE_TIMEOUT:
|
||||
return DisconnectReason::HANDSHAKE_TIMEOUT;
|
||||
|
||||
default:
|
||||
return DisconnectReason::OTHER;
|
||||
}
|
||||
}
|
||||
|
||||
bool NetworkConnection::useDhcp = false;
|
||||
NetworkConnection::Status NetworkConnection::status = Status::NONE;
|
||||
NetworkConnection::DisconnectReason NetworkConnection::disconnectReason = DisconnectReason::NONE;
|
||||
uint8_t NetworkConnection::rawDisconnectReason = 0;
|
||||
@@ -1,38 +0,0 @@
|
||||
#include <WiFi.h>
|
||||
|
||||
namespace NetworkUtils {
|
||||
struct NetworkConnection {
|
||||
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 uint8_t rawDisconnectReason;
|
||||
|
||||
static void setup(bool useDhcp);
|
||||
static void setUseDhcp(bool value);
|
||||
static void reset();
|
||||
static Status getStatus();
|
||||
static DisconnectReason getDisconnectReason();
|
||||
static void onEvent(WiFiEvent_t event, WiFiEventInfo_t info);
|
||||
|
||||
protected:
|
||||
static DisconnectReason convertDisconnectReason(uint8_t reason);
|
||||
static bool useDhcp;
|
||||
};
|
||||
}
|
||||
@@ -1,414 +0,0 @@
|
||||
#include <WiFi.h>
|
||||
#include <esp_wifi.h>
|
||||
#include <NetworkConnection.h>
|
||||
|
||||
namespace NetworkUtils {
|
||||
class NetworkMgr {
|
||||
public:
|
||||
typedef std::function<void()> YieldCallback;
|
||||
typedef std::function<void(unsigned int)> DelayCallback;
|
||||
|
||||
NetworkMgr() {
|
||||
NetworkConnection::setup(this->useDhcp);
|
||||
this->resetWifi();
|
||||
}
|
||||
|
||||
NetworkMgr* setYieldCallback(YieldCallback callback = nullptr) {
|
||||
this->yieldCallback = callback;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
NetworkMgr* setDelayCallback(DelayCallback callback = nullptr) {
|
||||
this->delayCallback = callback;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
NetworkMgr* setHostname(const char* value) {
|
||||
this->hostname = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
NetworkMgr* setApCredentials(const char* ssid, const char* password = nullptr, uint8_t channel = 0) {
|
||||
this->apName = ssid;
|
||||
this->apPassword = password;
|
||||
this->apChannel = channel;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
NetworkMgr* setStaCredentials(const char* ssid = nullptr, const char* password = nullptr, uint8_t channel = 0) {
|
||||
this->staSsid = ssid;
|
||||
this->staPassword = password;
|
||||
this->staChannel = channel;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
NetworkMgr* setUseDhcp(bool value) {
|
||||
this->useDhcp = value;
|
||||
NetworkConnection::setup(this->useDhcp);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
NetworkMgr* 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;
|
||||
}
|
||||
|
||||
NetworkMgr* 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() && NetworkConnection::getStatus() == NetworkConnection::Status::CONNECTED;
|
||||
}
|
||||
|
||||
bool isConnecting() {
|
||||
return this->isStaEnabled() && NetworkConnection::getStatus() == NetworkConnection::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;
|
||||
}
|
||||
|
||||
uint8_t getStaChannel() {
|
||||
return this->staChannel;
|
||||
}
|
||||
|
||||
bool resetWifi() {
|
||||
// set policy manual for work 13 ch
|
||||
{
|
||||
const wifi_country_t country = {"JP", 1, 14, CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER, WIFI_COUNTRY_POLICY_MANUAL};
|
||||
esp_wifi_set_country(&country);
|
||||
}
|
||||
|
||||
WiFi.persistent(false);
|
||||
#if ESP_ARDUINO_VERSION_MAJOR < 3
|
||||
WiFi.setAutoConnect(false);
|
||||
#endif
|
||||
WiFi.setAutoReconnect(false);
|
||||
|
||||
WiFi.setSleep(USE_BLE ? WIFI_PS_MIN_MODEM : WIFI_PS_NONE);
|
||||
|
||||
WiFi.softAPdisconnect();
|
||||
|
||||
WiFi.disconnect(false, true);
|
||||
|
||||
#if ESP_ARDUINO_VERSION_MAJOR < 3
|
||||
// Nothing. Because memory leaks when turn off WiFi on ESP32 SDK < 3.0.0
|
||||
return true;
|
||||
#else
|
||||
return WiFi.mode(WIFI_OFF);
|
||||
#endif
|
||||
}
|
||||
|
||||
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();
|
||||
NetworkConnection::reset();
|
||||
|
||||
} else {
|
||||
this->disconnect();
|
||||
}
|
||||
|
||||
if (!this->hasStaCredentials()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this->delayCallback(250);
|
||||
|
||||
if (this->setWifiHostname(this->hostname)) {
|
||||
Log.straceln(L_NETWORK, "Set hostname '%s': success", this->hostname);
|
||||
|
||||
} else {
|
||||
Log.serrorln(L_NETWORK, "Set hostname '%s': fail", this->hostname);
|
||||
}
|
||||
|
||||
if (!WiFi.mode((WiFiMode_t)(WiFi.getMode() | WIFI_STA))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this->delayCallback(250);
|
||||
|
||||
WiFi.setScanMethod(WIFI_ALL_CHANNEL_SCAN);
|
||||
WiFi.setSortMethod(WIFI_CONNECT_AP_BY_SIGNAL);
|
||||
|
||||
if (!this->useDhcp) {
|
||||
WiFi.begin(this->staSsid, this->staPassword, this->staChannel, nullptr, false);
|
||||
WiFi.config(this->staticIp, this->staticGateway, this->staticSubnet, this->staticDns);
|
||||
WiFi.reconnect();
|
||||
|
||||
} else {
|
||||
WiFi.begin(this->staSsid, this->staPassword, this->staChannel, nullptr, true);
|
||||
}
|
||||
|
||||
unsigned long beginConnectionTime = millis();
|
||||
while (millis() - beginConnectionTime < timeout) {
|
||||
this->delayCallback(100);
|
||||
|
||||
NetworkConnection::Status status = NetworkConnection::getStatus();
|
||||
if (status != NetworkConnection::Status::CONNECTING && status != NetworkConnection::Status::NONE) {
|
||||
return status == NetworkConnection::Status::CONNECTED;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void disconnect() {
|
||||
WiFi.disconnectAsync(false, true);
|
||||
|
||||
const unsigned long start = millis();
|
||||
while (WiFi.isConnected() && (millis() - start) < 5000) {
|
||||
this->delayCallback(100);
|
||||
}
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if (this->reconnectFlag) {
|
||||
this->delayCallback(5000);
|
||||
|
||||
Log.sinfoln(L_NETWORK, "Reconnecting...");
|
||||
this->reconnectFlag = false;
|
||||
this->disconnect();
|
||||
NetworkConnection::reset();
|
||||
this->delayCallback(1000);
|
||||
|
||||
} else if (this->isConnected() && !this->hasStaCredentials()) {
|
||||
Log.sinfoln(L_NETWORK, "Reset");
|
||||
this->resetWifi();
|
||||
NetworkConnection::reset();
|
||||
this->delayCallback(1000);
|
||||
|
||||
} else if (this->isConnected()) {
|
||||
if (!this->connected) {
|
||||
this->connectedTime = millis();
|
||||
this->connected = true;
|
||||
|
||||
Log.sinfoln(
|
||||
L_NETWORK,
|
||||
"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(L_NETWORK, "Stop AP because STA connected");
|
||||
|
||||
WiFi.mode(WIFI_STA);
|
||||
return;
|
||||
}
|
||||
|
||||
} else {
|
||||
if (this->connected) {
|
||||
this->disconnectedTime = millis();
|
||||
this->connected = false;
|
||||
|
||||
Log.sinfoln(
|
||||
L_NETWORK,
|
||||
"Disconnected, reason: %d, uptime: %lu s.",
|
||||
NetworkConnection::getDisconnectReason(),
|
||||
(millis() - this->connectedTime) / 1000
|
||||
);
|
||||
}
|
||||
|
||||
if (!this->hasStaCredentials() && !this->isApEnabled()) {
|
||||
Log.sinfoln(L_NETWORK, "No STA credentials, start AP");
|
||||
|
||||
WiFi.mode(WIFI_AP_STA);
|
||||
this->delayCallback(250);
|
||||
WiFi.softAP(this->apName, this->apPassword, this->apChannel);
|
||||
|
||||
} else if (!this->isApEnabled() && millis() - this->disconnectedTime > this->failedConnectTimeout) {
|
||||
Log.sinfoln(L_NETWORK, "Disconnected for a long time, start AP");
|
||||
|
||||
WiFi.mode(WIFI_AP_STA);
|
||||
this->delayCallback(250);
|
||||
WiFi.softAP(this->apName, this->apPassword, this->apChannel);
|
||||
|
||||
} else if (this->isConnecting() && millis() - this->prevReconnectingTime > this->resetConnectionTimeout) {
|
||||
Log.swarningln(L_NETWORK, "Connection timeout, reset wifi...");
|
||||
this->resetWifi();
|
||||
NetworkConnection::reset();
|
||||
this->delayCallback(250);
|
||||
|
||||
} else if (!this->isConnecting() && this->hasStaCredentials() && (!this->prevReconnectingTime || millis() - this->prevReconnectingTime > this->reconnectInterval)) {
|
||||
Log.sinfoln(L_NETWORK, "Try connect...");
|
||||
|
||||
NetworkConnection::reset();
|
||||
if (!this->connect(true, this->connectionTimeout)) {
|
||||
Log.straceln(L_NETWORK, "Connection failed. Status: %d, reason: %d, raw reason: %d", NetworkConnection::getStatus(), NetworkConnection::getDisconnectReason(), NetworkConnection::rawDisconnectReason);
|
||||
}
|
||||
|
||||
this->prevReconnectingTime = millis();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static uint8_t rssiToSignalQuality(short int rssi) {
|
||||
return constrain(map(rssi, -100, -50, 0, 100), 0, 100);
|
||||
}
|
||||
|
||||
static bool isHostnameValid(const char* value) {
|
||||
if (value == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
size_t len = strlen(value);
|
||||
if (len == 0 || len > 24 || value[0] == '-' || value[len - 1] == '-') {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
const char symbol = value[i];
|
||||
|
||||
// Lowercase ASCII letters.
|
||||
if (symbol >= 'a' && symbol <= 'z') {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Uppercase ASCII letters.
|
||||
if (symbol >= 'A' && symbol <= 'Z') {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Decimal digits.
|
||||
if (symbol >= '0' && symbol <= '9') {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Hyphens are allowed inside the hostname.
|
||||
if (symbol == '-') {
|
||||
continue;
|
||||
}
|
||||
|
||||
// All other characters are invalid.
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
protected:
|
||||
const unsigned int reconnectInterval = 15000;
|
||||
const unsigned int failedConnectTimeout = 185000;
|
||||
const unsigned int connectionTimeout = 10000;
|
||||
const unsigned int resetConnectionTimeout = 90000;
|
||||
|
||||
YieldCallback yieldCallback = []() {
|
||||
::yield();
|
||||
};
|
||||
DelayCallback delayCallback = [](unsigned int time) {
|
||||
::delay(time);
|
||||
};
|
||||
|
||||
const char* hostname = "esp";
|
||||
const char* apName = "ESP";
|
||||
const char* apPassword = nullptr;
|
||||
uint8_t apChannel = 1;
|
||||
|
||||
const char* staSsid = nullptr;
|
||||
const char* staPassword = nullptr;
|
||||
uint8_t staChannel = 0;
|
||||
|
||||
bool useDhcp = true;
|
||||
IPAddress staticIp;
|
||||
IPAddress staticGateway;
|
||||
IPAddress staticSubnet;
|
||||
IPAddress staticDns;
|
||||
|
||||
bool connected = false;
|
||||
bool reconnectFlag = false;
|
||||
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);
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
#include <FS.h>
|
||||
#include <detail/mimetable.h>
|
||||
|
||||
using namespace mime;
|
||||
|
||||
class StaticPage : public RequestHandler {
|
||||
public:
|
||||
typedef std::function<bool(HTTPMethod, const String&)> CanHandleCallback;
|
||||
typedef std::function<bool()> BeforeSendCallback;
|
||||
|
||||
template <class T>
|
||||
StaticPage(const char* uri, FS* fs, T path, const char* cacheHeader = nullptr) {
|
||||
this->uri = uri;
|
||||
this->fs = fs;
|
||||
this->path = path;
|
||||
this->cacheHeader = cacheHeader;
|
||||
}
|
||||
|
||||
StaticPage* setCanHandleCallback(CanHandleCallback callback = nullptr) {
|
||||
this->canHandleCallback = callback;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
StaticPage* setBeforeSendCallback(BeforeSendCallback callback = nullptr) {
|
||||
this->beforeSendCallback = callback;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
bool canHandle(WebServer &server, HTTPMethod method, const String &uri) override {
|
||||
return this->canHandle(method, uri);
|
||||
}
|
||||
|
||||
bool canHandle(HTTPMethod method, const String& uri) override {
|
||||
return method == HTTP_GET && uri.equals(this->uri) && (!this->canHandleCallback || this->canHandleCallback(method, uri));
|
||||
}
|
||||
|
||||
bool handle(WebServer& server, HTTPMethod method, const String& uri) override {
|
||||
if (!this->canHandle(method, uri)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this->beforeSendCallback && !this->beforeSendCallback()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (server._eTagEnabled) {
|
||||
if (this->eTag.isEmpty()) {
|
||||
if (server._eTagFunction) {
|
||||
this->eTag = (server._eTagFunction)(*this->fs, this->path);
|
||||
}
|
||||
}
|
||||
|
||||
if (!this->eTag.isEmpty() && server.header("If-None-Match").equals(this->eTag.c_str())) {
|
||||
server.send(304);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!this->path.endsWith(mimeTable[gz].endsWith) && !this->fs->exists(path)) {
|
||||
String pathWithGz = this->path + mimeTable[gz].endsWith;
|
||||
|
||||
if (this->fs->exists(pathWithGz)) {
|
||||
this->path += mimeTable[gz].endsWith;
|
||||
}
|
||||
}
|
||||
|
||||
File file = this->fs->open(this->path, "r");
|
||||
if (!file) {
|
||||
return false;
|
||||
|
||||
} else if (file.isDirectory()) {
|
||||
file.close();
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this->cacheHeader != nullptr) {
|
||||
server.sendHeader("Cache-Control", this->cacheHeader);
|
||||
}
|
||||
|
||||
if (server._eTagEnabled && !this->eTag.isEmpty()) {
|
||||
server.sendHeader("ETag", this->eTag);
|
||||
}
|
||||
|
||||
server.streamFile(file, "text/html", 200);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
protected:
|
||||
FS* fs = nullptr;
|
||||
CanHandleCallback canHandleCallback;
|
||||
BeforeSendCallback beforeSendCallback;
|
||||
String eTag;
|
||||
const char* uri = nullptr;
|
||||
String path;
|
||||
const char* cacheHeader = nullptr;
|
||||
};
|
||||
@@ -1,4 +1,6 @@
|
||||
#include <Arduino.h>
|
||||
#include <esp_log.h>
|
||||
#include <strings_shared.h>
|
||||
|
||||
class UpgradeHandler : public AsyncWebHandler {
|
||||
public:
|
||||
@@ -27,12 +29,13 @@ public:
|
||||
} UpgradeResult;
|
||||
|
||||
typedef std::function<bool(AsyncWebServerRequest *request, UpgradeType)> BeforeUpgradeCallback;
|
||||
// A null request reports an upload disconnected after preparation was accepted.
|
||||
typedef std::function<void(AsyncWebServerRequest *request, const UpgradeResult&, const UpgradeResult&)> AfterUpgradeCallback;
|
||||
|
||||
explicit UpgradeHandler(AsyncURIMatcher uri) : uri(uri) {}
|
||||
|
||||
bool canHandle(AsyncWebServerRequest *request) const final {
|
||||
if (!request->isHTTP()) {
|
||||
if (!request->isHTTP() || request->method() != HTTP_POST) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -52,18 +55,28 @@ public:
|
||||
}
|
||||
|
||||
void handleRequest(AsyncWebServerRequest *request) final {
|
||||
if (this->afterUpgradeCallback) {
|
||||
this->afterUpgradeCallback(request, this->firmwareResult, this->filesystemResult);
|
||||
if (request->getResponse()) {
|
||||
return;
|
||||
}
|
||||
|
||||
this->firmwareResult.status = UpgradeStatus::NONE;
|
||||
this->firmwareResult.error.clear();
|
||||
if (this->activeRequest != request) {
|
||||
request->send(this->activeRequest ? 409 : 400);
|
||||
return;
|
||||
}
|
||||
|
||||
this->filesystemResult.status = UpgradeStatus::NONE;
|
||||
this->filesystemResult.error.clear();
|
||||
finishRequest(request);
|
||||
}
|
||||
|
||||
void handleUpload(AsyncWebServerRequest *request, const String &fileName, size_t index, uint8_t *data, size_t dataLength, bool isFinal) final {
|
||||
if (request->getResponse()) {
|
||||
return;
|
||||
}
|
||||
if (this->activeRequest && this->activeRequest != request) {
|
||||
// Keep the rejection on this request even if the active upload finishes first.
|
||||
request->send(409);
|
||||
return;
|
||||
}
|
||||
|
||||
UpgradeResult* result = nullptr;
|
||||
|
||||
if (!request->hasParam(asyncsrv::T_name, true, true)) {
|
||||
@@ -97,6 +110,15 @@ public:
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this->activeRequest) {
|
||||
this->activeRequest = request;
|
||||
request->onDisconnect([this, request] {
|
||||
if (this->activeRequest == request) {
|
||||
finishRequest(nullptr);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// check result status
|
||||
if (result->status != UpgradeStatus::NONE) {
|
||||
return;
|
||||
@@ -106,6 +128,7 @@ public:
|
||||
result->status = UpgradeStatus::PROHIBITED;
|
||||
return;
|
||||
}
|
||||
this->preparationAccepted = true;
|
||||
|
||||
if (!fileName.length()) {
|
||||
result->status = UpgradeStatus::NO_FILE;
|
||||
@@ -132,11 +155,11 @@ public:
|
||||
result->status = UpgradeStatus::ERROR_ON_START;
|
||||
result->error = Update.errorString();
|
||||
|
||||
Log.serrorln(L_PORTAL_OTA, "File '%s', on start: %s", fileName.c_str(), result->error.c_str());
|
||||
ESP_LOGE(L_PORTAL_OTA, "File '%s', on start: %s", fileName.c_str(), result->error.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
Log.sinfoln(L_PORTAL_OTA, "File '%s', started", fileName.c_str());
|
||||
ESP_LOGI(L_PORTAL_OTA, "File '%s', started", fileName.c_str());
|
||||
}
|
||||
|
||||
if (dataLength) {
|
||||
@@ -145,7 +168,7 @@ public:
|
||||
result->status = UpgradeStatus::ERROR_ON_WRITE;
|
||||
result->error = Update.errorString();
|
||||
|
||||
Log.serrorln(
|
||||
ESP_LOGE(
|
||||
L_PORTAL_OTA, "File '%s', on write %d bytes, %d of %d bytes",
|
||||
fileName.c_str(),
|
||||
dataLength,
|
||||
@@ -156,7 +179,7 @@ public:
|
||||
}
|
||||
|
||||
result->progress += dataLength;
|
||||
Log.sinfoln(
|
||||
ESP_LOGI(
|
||||
L_PORTAL_OTA, "File '%s', write %d bytes, %d of %d bytes",
|
||||
fileName.c_str(),
|
||||
dataLength,
|
||||
@@ -170,7 +193,7 @@ public:
|
||||
Update.end(false);
|
||||
result->status = UpgradeStatus::SIZE_MISMATCH;
|
||||
|
||||
Log.serrorln(
|
||||
ESP_LOGE(
|
||||
L_PORTAL_OTA, "File '%s', size mismatch: %d of %d bytes",
|
||||
fileName.c_str(),
|
||||
result->progress,
|
||||
@@ -185,12 +208,12 @@ public:
|
||||
result->status = UpgradeStatus::ERROR_ON_FINISH;
|
||||
result->error = Update.errorString();
|
||||
|
||||
Log.serrorln(L_PORTAL_OTA, "File '%s', on finish: %s", fileName.c_str(), result->error.c_str());
|
||||
ESP_LOGE(L_PORTAL_OTA, "File '%s', on finish: %s", fileName.c_str(), result->error.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
result->status = UpgradeStatus::SUCCESS;
|
||||
Log.sinfoln(L_PORTAL_OTA, "File '%s': finish", fileName.c_str());
|
||||
ESP_LOGI(L_PORTAL_OTA, "File '%s': finish", fileName.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,10 +222,31 @@ public:
|
||||
}
|
||||
|
||||
protected:
|
||||
void finishRequest(AsyncWebServerRequest *request) {
|
||||
if (request) {
|
||||
request->onDisconnect(nullptr);
|
||||
}
|
||||
if (Update.isRunning()) {
|
||||
// Abort only the unfinished file; an earlier successful firmware still needs a restart.
|
||||
Update.abort();
|
||||
}
|
||||
if (this->afterUpgradeCallback && (request || this->preparationAccepted)) {
|
||||
this->afterUpgradeCallback(request, this->firmwareResult, this->filesystemResult);
|
||||
}
|
||||
|
||||
this->activeRequest = nullptr;
|
||||
this->preparationAccepted = false;
|
||||
this->firmwareResult = {UpgradeType::FIRMWARE, UpgradeStatus::NONE};
|
||||
this->filesystemResult = {UpgradeType::FILESYSTEM, UpgradeStatus::NONE};
|
||||
}
|
||||
|
||||
BeforeUpgradeCallback beforeUpgradeCallback;
|
||||
AfterUpgradeCallback afterUpgradeCallback;
|
||||
AsyncURIMatcher uri;
|
||||
|
||||
// Upload, completion and disconnect callbacks share the AsyncTCP worker.
|
||||
AsyncWebServerRequest* activeRequest = nullptr;
|
||||
bool preparationAccepted = false;
|
||||
UpgradeResult firmwareResult{UpgradeType::FIRMWARE, UpgradeStatus::NONE};
|
||||
UpgradeResult filesystemResult{UpgradeType::FILESYSTEM, UpgradeStatus::NONE};
|
||||
};
|
||||
Reference in new issue
Block a user