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