ESPHome 2026.1.4
Loading...
Searching...
No Matches
improv_base.cpp
Go to the documentation of this file.
1#include "improv_base.h"
2
3#include <cstring>
7
8namespace esphome {
9namespace improv_base {
10
11#if defined(USE_ESP32_IMPROV_NEXT_URL) || defined(USE_IMPROV_SERIAL_NEXT_URL)
12static constexpr const char DEVICE_NAME_PLACEHOLDER[] = "{{device_name}}";
13static constexpr size_t DEVICE_NAME_PLACEHOLDER_LEN = sizeof(DEVICE_NAME_PLACEHOLDER) - 1;
14static constexpr const char IP_ADDRESS_PLACEHOLDER[] = "{{ip_address}}";
15static constexpr size_t IP_ADDRESS_PLACEHOLDER_LEN = sizeof(IP_ADDRESS_PLACEHOLDER) - 1;
16
18static char *copy_to_buffer(char *dest, const char *end, const char *src) {
19 if (src == nullptr) {
20 return dest;
21 }
22 while (*src != '\0' && dest < end) {
23 *dest++ = *src++;
24 }
25 return dest;
26}
27
28size_t ImprovBase::get_formatted_next_url_(char *buffer, size_t buffer_size) {
29 if (this->next_url_ == nullptr || buffer_size == 0) {
30 if (buffer_size > 0) {
31 buffer[0] = '\0';
32 }
33 return 0;
34 }
35
36 // Get IP address once for replacement
37 const char *ip_str = nullptr;
38 char ip_buffer[network::IP_ADDRESS_BUFFER_SIZE];
39 for (auto &ip : network::get_ip_addresses()) {
40 if (ip.is_ip4()) {
41 ip.str_to(ip_buffer);
42 ip_str = ip_buffer;
43 break;
44 }
45 }
46
47 const char *device_name = App.get_name().c_str();
48 char *out = buffer;
49 const char *end = buffer + buffer_size - 1;
50
51 // Note: {{esphome_version}} is replaced at code generation time in Python
52 for (const char *p = this->next_url_; *p != '\0' && out < end;) {
53 if (strncmp(p, DEVICE_NAME_PLACEHOLDER, DEVICE_NAME_PLACEHOLDER_LEN) == 0) {
54 out = copy_to_buffer(out, end, device_name);
55 p += DEVICE_NAME_PLACEHOLDER_LEN;
56 } else if (ip_str != nullptr && strncmp(p, IP_ADDRESS_PLACEHOLDER, IP_ADDRESS_PLACEHOLDER_LEN) == 0) {
57 out = copy_to_buffer(out, end, ip_str);
58 p += IP_ADDRESS_PLACEHOLDER_LEN;
59 } else {
60 *out++ = *p++;
61 }
62 }
63 *out = '\0';
64 return out - buffer;
65}
66#endif
67
68} // namespace improv_base
69} // namespace esphome
const std::string & get_name() const
Get the name of this Application set by pre_setup().
size_t get_formatted_next_url_(char *buffer, size_t buffer_size)
Format next_url_ into buffer, replacing placeholders. Returns length written.
network::IPAddresses get_ip_addresses()
Definition util.cpp:66
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
Application App
Global storage of Application pointer - only one Application can exist.
uint8_t end[39]
Definition sun_gtil2.cpp:17