ESPHome  2024.11.0
utils.cpp
Go to the documentation of this file.
1 #ifdef USE_ESP_IDF
2 #include <memory>
3 #include "esphome/core/log.h"
4 #include "esphome/core/helpers.h"
5 #include "http_parser.h"
6 
7 #include "utils.h"
8 
9 namespace esphome {
10 namespace web_server_idf {
11 
12 static const char *const TAG = "web_server_idf_utils";
13 
14 void url_decode(char *str) {
15  char *ptr = str, buf;
16  for (; *str; str++, ptr++) {
17  if (*str == '%') {
18  str++;
19  if (parse_hex(str, 2, reinterpret_cast<uint8_t *>(&buf), 1) == 2) {
20  *ptr = buf;
21  str++;
22  } else {
23  str--;
24  *ptr = *str;
25  }
26  } else if (*str == '+') {
27  *ptr = ' ';
28  } else {
29  *ptr = *str;
30  }
31  }
32  *ptr = *str;
33 }
34 
35 bool request_has_header(httpd_req_t *req, const char *name) { return httpd_req_get_hdr_value_len(req, name); }
36 
37 optional<std::string> request_get_header(httpd_req_t *req, const char *name) {
38  size_t len = httpd_req_get_hdr_value_len(req, name);
39  if (len == 0) {
40  return {};
41  }
42 
43  std::string str;
44  str.resize(len);
45 
46  auto res = httpd_req_get_hdr_value_str(req, name, &str[0], len + 1);
47  if (res != ESP_OK) {
48  return {};
49  }
50 
51  return {str};
52 }
53 
55  auto len = httpd_req_get_url_query_len(req);
56  if (len == 0) {
57  return {};
58  }
59 
60  std::string str;
61  str.resize(len);
62 
63  auto res = httpd_req_get_url_query_str(req, &str[0], len + 1);
64  if (res != ESP_OK) {
65  ESP_LOGW(TAG, "Can't get query for request: %s", esp_err_to_name(res));
66  return {};
67  }
68 
69  return {str};
70 }
71 
72 optional<std::string> query_key_value(const std::string &query_url, const std::string &key) {
73  if (query_url.empty()) {
74  return {};
75  }
76 
77  auto val = std::unique_ptr<char[]>(new char[query_url.size()]);
78  if (!val) {
79  ESP_LOGE(TAG, "Not enough memory to the query key value");
80  return {};
81  }
82 
83  if (httpd_query_key_value(query_url.c_str(), key.c_str(), val.get(), query_url.size()) != ESP_OK) {
84  return {};
85  }
86 
87  url_decode(val.get());
88  return {val.get()};
89 }
90 
91 } // namespace web_server_idf
92 } // namespace esphome
93 #endif // USE_ESP_IDF
const char * name
Definition: stm32flash.h:78
size_t parse_hex(const char *str, size_t length, uint8_t *data, size_t count)
Parse bytes from a hex-encoded string into a byte array.
Definition: helpers.cpp:333
mopeka_std_values val[4]
optional< std::string > request_get_header(httpd_req_t *req, const char *name)
Definition: utils.cpp:37
bool request_has_header(httpd_req_t *req, const char *name)
Definition: utils.cpp:35
void url_decode(char *str)
Definition: utils.cpp:14
optional< std::string > query_key_value(const std::string &query_url, const std::string &key)
Definition: utils.cpp:72
optional< std::string > request_get_url_query(httpd_req_t *req)
Definition: utils.cpp:54
std::string size_t len
Definition: helpers.h:293
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7