123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- #ifndef KBF_HTTP_CLIENT_H
- #define KBF_HTTP_CLIENT_H
- #include <string>
- #include <memory>
- #include <esp_err.h>
- #include <esp_http_client.h>
- #include "kbf/http/common.h"
- using std::string;
- using std::shared_ptr;
- namespace kbf::http {
- /**
- * @brief HTTP Client.
- *
- * @note May only perform 1 request at a time, but can be (and should be) reused afterwards.
- */
- class Client {
- public:
- /** @brief Tag used for logging. */
- static constexpr const char *TAG = "kbf::http::Client";
- /**
- * @brief Constructor.
- *
- * @warning Async mode is only supported by IDF for HTTPS.
- *
- * @param async perform request asynchronously; default is false
- */
- explicit Client(bool async = false);
- /**
- * @brief Destructor.
- *
- * Calls esp_http_client_cleanup().
- */
- ~Client();
- /**
- * @brief Performs an HTTP GET.
- *
- * Calls onSuccess() when a response is received (even if it's a HTTP 4XX), or onError() on failure
- * (e.g. socket error)
- *
- * @param url_param url to fetch
- */
- shared_ptr<Response> get(const string &url_param);
- /**
- * @brief Called on HTTP_EVENT_ERROR event.
- *
- * @note This will be called for low-level errors (e.g. socket error). If the request went through normally,
- * but the server responded with an error code (HTTP 4XX), onSuccess() will be called instead.
- *
- * @param client reference to the Client that issued the request
- */
- void (*onError)(Client &client) = nullptr;
- /**
- * @brief Called after the response is received.
- *
- * @note "Success" here means that the request went through and a response was received.
- * This method will be called even if the server returned an error status (HTTP 4XX)
- *
- * @param client reference to the Client that issued the request
- * @param response struct containing the HTTP response data
- */
- void (*onSuccess)(Client &client, const Response &response) = nullptr;
- /**
- * @brief Returns whether a request is currently in progress.
- *
- * @return true if a request is currently in progress; false otherwise
- */
- [[nodiscard]] bool isRunning() const { return running; }
- private:
- void init();
- static void updateResponse(Client &client);
- /**
- * @brief Processes events from esp_http_client.
- *
- * @return
- */
- static esp_err_t handleHttpEvent(esp_http_client_event_t *);
- esp_http_client_handle_t handle{};
- string buffer;
- shared_ptr<Response> response;
- bool running = false;
- bool retry = false;
- bool async;
- };
- }
- #endif //KBF_HTTP_CLIENT_H
|