Files
espasynchttpreq/src/asynchttprequest.cpp
T

347 lines
9.6 KiB
C++
Raw Normal View History

2021-04-07 20:03:49 +02:00
#include "asynchttprequest.h"
#include "sdkconfig.h"
#define LOG_LOCAL_LEVEL CONFIG_LOG_LOCAL_LEVEL_ASYNC_HTTP
// system includes
#include <chrono>
#include <string_view>
2021-04-07 20:03:49 +02:00
#include <cstring>
#include <assert.h>
// esp-idf includes
#include <esp_log.h>
2021-08-04 22:10:25 +02:00
// 3rdparty lib includes
#include <fmt/core.h>
2021-04-07 20:03:49 +02:00
// local includes
#include "cleanuphelper.h"
#include "taskutils.h"
#include "tickchrono.h"
using namespace std::chrono_literals;
namespace {
constexpr const char * const TAG = "ASYNC_HTTP";
constexpr int TASK_RUNNING = BIT0;
constexpr int START_REQUEST_BIT = BIT1;
constexpr int REQUEST_RUNNING_BIT = BIT2;
constexpr int REQUEST_FINISHED_BIT = BIT3;
constexpr int END_TASK_BIT = BIT4;
constexpr int TASK_ENDED = BIT5;
2021-04-07 20:03:49 +02:00
} // namespace
AsyncHttpRequest::AsyncHttpRequest(const char *taskName, espcpputils::CoreAffinity coreAffinity) :
m_taskName{taskName},
2021-04-07 20:03:49 +02:00
m_coreAffinity{coreAffinity}
{
2021-08-04 22:10:25 +02:00
assert(m_eventGroup.handle);
2021-04-07 20:03:49 +02:00
}
AsyncHttpRequest::~AsyncHttpRequest()
{
endTask();
}
2021-08-04 22:10:25 +02:00
tl::expected<void, std::string> AsyncHttpRequest::startTask()
{
2021-08-04 22:10:25 +02:00
if (const auto bits = m_eventGroup.getBits();
bits & TASK_RUNNING || m_taskHandle)
{
constexpr auto msg = "task already started";
ESP_LOGW(TAG, "%s", msg);
2021-08-04 22:10:25 +02:00
return tl::make_unexpected(msg);
}
2021-08-04 22:10:25 +02:00
m_eventGroup.clearBits(TASK_RUNNING | START_REQUEST_BIT | REQUEST_RUNNING_BIT | REQUEST_FINISHED_BIT | END_TASK_BIT | TASK_ENDED);
2021-08-04 22:10:25 +02:00
const auto result = espcpputils::createTask(requestTask, m_taskName, 2048, this, 10, &m_taskHandle, m_coreAffinity);
if (result != pdPASS)
{
2021-08-04 22:10:25 +02:00
auto msg = fmt::format("failed creating http task {}", result);
ESP_LOGE(TAG, "%.*s", msg.size(), msg.data());
return tl::make_unexpected(std::move(msg));
}
2021-08-04 22:10:25 +02:00
if (!m_taskHandle)
{
constexpr auto msg = "http task handle is null";
ESP_LOGW(TAG, "%s", msg);
2021-08-04 22:10:25 +02:00
return tl::make_unexpected(msg);
}
ESP_LOGD(TAG, "created http task %s", m_taskName);
2021-08-04 22:10:25 +02:00
if (const auto bits = m_eventGroup.waitBits(TASK_RUNNING, false, false, std::chrono::ceil<espcpputils::ticks>(1s).count());
bits & TASK_RUNNING)
2021-08-04 22:10:25 +02:00
return {};
ESP_LOGW(TAG, "http task %s TASK_RUNNING bit not yet set...", m_taskName);
while (true)
2021-08-04 22:10:25 +02:00
if (const auto bits = m_eventGroup.waitBits(TASK_RUNNING, false, false, portMAX_DELAY);
bits & TASK_RUNNING)
break;
2021-08-04 22:10:25 +02:00
return {};
}
2021-08-04 22:10:25 +02:00
tl::expected<void, std::string> AsyncHttpRequest::endTask()
{
2021-08-04 22:10:25 +02:00
if (const auto bits = m_eventGroup.getBits();
!(bits & TASK_RUNNING))
2021-08-04 22:10:25 +02:00
return {};
else if (bits & END_TASK_BIT)
{
constexpr auto msg = "Another end request is already pending";
ESP_LOGE(TAG, "%s", msg);
2021-08-04 22:10:25 +02:00
return tl::make_unexpected(msg);
}
2021-08-04 22:10:25 +02:00
m_eventGroup.setBits(END_TASK_BIT);
2021-08-04 22:10:25 +02:00
if (const auto bits = m_eventGroup.waitBits(TASK_ENDED, true, false, std::chrono::ceil<espcpputils::ticks>(1s).count());
bits & TASK_ENDED)
{
ESP_LOGD(TAG, "http task %s ended", m_taskName);
2021-08-04 22:10:25 +02:00
return {};
}
ESP_LOGW(TAG, "http task %s TASK_ENDED bit not yet set...", m_taskName);
while (true)
2021-08-04 22:10:25 +02:00
if (const auto bits = m_eventGroup.waitBits(TASK_ENDED, true, false, portMAX_DELAY);
bits & TASK_ENDED)
break;
ESP_LOGD(TAG, "http task %s ended", m_taskName);
2021-08-04 22:10:25 +02:00
return {};
}
2021-08-04 22:10:25 +02:00
tl::expected<void, std::string> AsyncHttpRequest::createClient(std::string_view url)
{
2021-08-04 22:10:25 +02:00
if (m_client)
{
2021-08-04 22:10:25 +02:00
constexpr auto msg = "m_client already created";
ESP_LOGE(TAG, "%s", msg);
2021-08-04 22:10:25 +02:00
return tl::make_unexpected(msg);
}
esp_http_client_config_t config{};
2021-08-04 22:10:25 +02:00
config.url = url.data();
config.event_handler = httpEventHandler;
config.user_data = this;
2021-08-04 22:10:25 +02:00
m_client = espcpputils::http_client{&config};
2021-08-04 22:10:25 +02:00
if (!m_client)
{
constexpr auto msg = "http client could not be constructed";
ESP_LOGE(TAG, "%s", msg);
2021-08-04 22:10:25 +02:00
return tl::make_unexpected(msg);
}
ESP_LOGD(TAG, "created http client %s", m_taskName);
2021-08-04 22:10:25 +02:00
return {};
}
2021-08-04 22:10:25 +02:00
tl::expected<void, std::string> AsyncHttpRequest::deleteClient()
{
2021-08-04 22:10:25 +02:00
if (!m_client)
return {};
if (inProgress())
{
constexpr auto msg = "another request still in progress";
ESP_LOGW(TAG, "%s", msg);
2021-08-04 22:10:25 +02:00
return tl::make_unexpected(msg);
}
2021-08-04 22:10:25 +02:00
m_client = {};
2021-08-04 22:10:25 +02:00
return {};
2021-04-07 20:03:49 +02:00
}
2021-08-04 22:10:25 +02:00
tl::expected<void, std::string> AsyncHttpRequest::start(std::string_view url)
2021-04-07 20:03:49 +02:00
{
2021-08-04 22:10:25 +02:00
if (!m_taskHandle)
2021-04-07 20:03:49 +02:00
{
2021-08-04 22:10:25 +02:00
if (const auto result = startTask(); !result)
return tl::make_unexpected(std::move(result).error());
2021-04-07 20:03:49 +02:00
}
if (inProgress())
{
constexpr auto msg = "another request still in progress";
ESP_LOGW(TAG, "%s", msg);
2021-08-04 22:10:25 +02:00
return tl::make_unexpected(msg);
}
2021-08-04 22:10:25 +02:00
if (!m_client)
{
2021-08-04 22:10:25 +02:00
if (const auto result = createClient(url); !result)
return tl::make_unexpected(std::move(result).error());
}
else
{
2021-08-04 22:10:25 +02:00
const auto result = m_client.set_url(url);
ESP_LOG_LEVEL_LOCAL((result == ESP_OK ? ESP_LOG_DEBUG : ESP_LOG_ERROR), TAG, "m_client.set_url() returned: %s (%.*s)", esp_err_to_name(result), url.size(), url.data());
if (result != ESP_OK)
2021-08-04 22:10:25 +02:00
return tl::make_unexpected(fmt::format("m_client.set_url() failed: {} ({})", esp_err_to_name(result), url));
}
2021-08-04 22:10:25 +02:00
m_buf.clear();
2021-04-07 20:03:49 +02:00
clearFinished();
2021-08-04 22:10:25 +02:00
m_eventGroup.setBits(START_REQUEST_BIT);
2021-04-07 20:03:49 +02:00
2021-08-04 22:10:25 +02:00
return {};
2021-04-07 20:03:49 +02:00
}
bool AsyncHttpRequest::inProgress() const
{
2021-08-04 22:10:25 +02:00
return m_eventGroup.getBits() & (START_REQUEST_BIT | REQUEST_RUNNING_BIT);
}
2021-04-07 20:03:49 +02:00
bool AsyncHttpRequest::finished() const
{
2021-08-04 22:10:25 +02:00
return m_eventGroup.getBits() & REQUEST_FINISHED_BIT;
2021-04-07 20:03:49 +02:00
}
2021-08-04 22:10:25 +02:00
tl::expected<void, std::string> AsyncHttpRequest::result() const
2021-04-07 20:03:49 +02:00
{
2021-08-04 22:10:25 +02:00
if (const auto bits = m_eventGroup.getBits();
bits & REQUEST_RUNNING_BIT)
{
constexpr auto msg = "request still running";
ESP_LOGW(TAG, "%s", msg);
2021-08-04 22:10:25 +02:00
return tl::make_unexpected(msg);
}
else if (!(bits & REQUEST_FINISHED_BIT))
{
constexpr auto msg = "request not finished";
ESP_LOGW(TAG, "%s", msg);
2021-08-04 22:10:25 +02:00
return tl::make_unexpected(msg);
}
2021-08-04 22:10:25 +02:00
if (m_result != ESP_OK)
return tl::make_unexpected(fmt::format("http request failed: {}", esp_err_to_name(m_result)));
2021-04-07 20:03:49 +02:00
2021-08-04 22:10:25 +02:00
if (m_statusCode != HttpStatus_Ok)
return tl::make_unexpected(fmt::format("http request failed: {}", m_statusCode));
2021-04-07 20:03:49 +02:00
2021-08-04 22:10:25 +02:00
return {};
2021-04-07 20:03:49 +02:00
}
void AsyncHttpRequest::clearFinished()
2021-04-07 20:03:49 +02:00
{
2021-08-04 22:10:25 +02:00
m_eventGroup.clearBits(REQUEST_FINISHED_BIT);
2021-04-07 20:03:49 +02:00
}
esp_err_t AsyncHttpRequest::httpEventHandler(esp_http_client_event_t *evt)
{
auto _this = reinterpret_cast<AsyncHttpRequest*>(evt->user_data);
2021-04-07 20:03:49 +02:00
assert(_this);
switch(evt->event_id) {
case HTTP_EVENT_ON_HEADER:
if (evt->header_key && evt->header_value)
{
if (strcasecmp(evt->header_key, "Content-Length") == 0)
{
unsigned int size;
if (std::sscanf(evt->header_value, "%u", &size) == 1)
{
//ESP_LOGD(TAG, "reserving %u bytes for http buffer", size);
2021-08-04 22:10:25 +02:00
_this->m_buf.reserve(size);
2021-04-07 20:03:49 +02:00
}
else
{
ESP_LOGW(TAG, "Could not parse Content-Length header \"%s\"", evt->header_value);
}
}
}
break;
case HTTP_EVENT_ON_DATA:
if (!evt->data)
ESP_LOGW(TAG, "handler with invalid data ptr");
else if (evt->data_len <= 0)
ESP_LOGW(TAG, "handler with invalid data_len %i", evt->data_len);
else
2021-08-04 22:10:25 +02:00
_this->m_buf += std::string_view((const char *)evt->data, evt->data_len);
2021-04-07 20:03:49 +02:00
break;
default:;
}
return ESP_OK;
}
void AsyncHttpRequest::requestTask(void *ptr)
{
auto _this = reinterpret_cast<AsyncHttpRequest*>(ptr);
2021-04-07 20:03:49 +02:00
assert(_this);
2021-08-04 22:10:25 +02:00
_this->requestTask();
}
void AsyncHttpRequest::requestTask()
{
m_eventGroup.setBits(TASK_RUNNING);
// cleanup on task exit
auto helper = cpputils::makeCleanupHelper([&](){
2021-08-04 22:10:25 +02:00
m_eventGroup.clearBits(TASK_RUNNING);
m_eventGroup.setBits(TASK_ENDED);
m_taskHandle = NULL;
vTaskDelete(NULL);
});
2021-04-07 20:03:49 +02:00
while (true)
{
2021-08-04 22:10:25 +02:00
if (const auto bits = m_eventGroup.waitBits(START_REQUEST_BIT|END_TASK_BIT, true, false, portMAX_DELAY);
bits & END_TASK_BIT)
break;
else if (!(bits & START_REQUEST_BIT))
continue;
2021-08-04 22:10:25 +02:00
assert(m_client);
2021-04-07 20:03:49 +02:00
{
2021-08-04 22:10:25 +02:00
const auto bits = m_eventGroup.getBits();
assert(!(bits & START_REQUEST_BIT));
assert(!(bits & REQUEST_RUNNING_BIT));
assert(!(bits & REQUEST_FINISHED_BIT));
2021-04-07 20:03:49 +02:00
}
2021-08-04 22:10:25 +02:00
m_eventGroup.setBits(REQUEST_RUNNING_BIT);
auto helper2 = cpputils::makeCleanupHelper([&](){
2021-08-04 22:10:25 +02:00
m_eventGroup.clearBits(REQUEST_RUNNING_BIT);
m_eventGroup.setBits(REQUEST_FINISHED_BIT);
});
2021-04-07 20:03:49 +02:00
{
esp_err_t result;
do
2021-08-04 22:10:25 +02:00
result = m_client.perform();
while (result == EAGAIN || result == EINPROGRESS);
2021-08-04 22:10:25 +02:00
ESP_LOG_LEVEL_LOCAL((result == ESP_OK ? ESP_LOG_VERBOSE : ESP_LOG_ERROR), TAG, "m_client.perform() returned: %s", esp_err_to_name(result));
m_result = result;
m_statusCode = m_client.get_status_code();
2021-04-07 20:03:49 +02:00
}
// workaround for esp-idf bug, every request after the first one fails with ESP_ERR_HTTP_FETCH_HEADER
2021-08-04 22:10:25 +02:00
const auto result = m_client.close();
ESP_LOG_LEVEL_LOCAL((result == ESP_OK ? ESP_LOG_VERBOSE : ESP_LOG_ERROR), TAG, "m_client.close() returned: %s", esp_err_to_name(result));
if (result != ESP_OK)
2021-08-04 22:10:25 +02:00
m_client = {};
2021-04-07 20:03:49 +02:00
}
}