ESPHome 2026.7.3
Loading...
Searching...
No Matches
captive_portal.cpp
Go to the documentation of this file.
1#include "captive_portal.h"
2#ifdef USE_CAPTIVE_PORTAL
3#include "esphome/core/log.h"
6#include "captive_index.h"
7#include "json_escape.h"
8
10
11static const char *const TAG = "captive_portal";
12
13void CaptivePortal::handle_config(AsyncWebServerRequest *request) {
14 AsyncResponseStream *stream = request->beginResponseStream(ESPHOME_F("application/json"));
15 stream->addHeader(ESPHOME_F("cache-control"), ESPHOME_F("public, max-age=0, must-revalidate"));
16 char mac_s[18];
17 const char *mac_str = get_mac_address_pretty_into_buffer(mac_s);
18#ifdef USE_ESP8266
19 stream->print(ESPHOME_F("{\"mac\":\""));
20 stream->print(mac_str);
21 stream->print(ESPHOME_F("\",\"name\":\""));
22 stream->print(App.get_name().c_str());
23 stream->print(ESPHOME_F("\",\"aps\":[{}"));
24#else
25 stream->printf(R"({"mac":"%s","name":"%s","aps":[{})", mac_str, App.get_name().c_str());
26#endif
27
28 // An SSID can contain a " or \ that would break the JSON, so escape it before writing it out. An SSID is at most
29 // 32 bytes (IEEE 802.11), so this is large enough that nothing is ever dropped. Reused for every scan result.
30 char escaped_ssid[32 * JSON_ESCAPE_MAX_EXPANSION + 1];
31 {
32 // Invariant: only bounded in-memory work under the lock; the network send
33 // happens later in request->send()
35 for (const auto &scan : wifi::global_wifi_component->get_scan_result()) {
36 if (scan.get_is_hidden())
37 continue;
38
39 json_escape_into_buffer(escaped_ssid, scan.get_ssid());
40#ifdef USE_ESP8266
41 stream->print(ESPHOME_F(",{\"ssid\":\""));
42 stream->print(escaped_ssid);
43 stream->print(ESPHOME_F("\",\"rssi\":"));
44 stream->print(scan.get_rssi());
45 stream->print(ESPHOME_F(",\"lock\":"));
46 stream->print(scan.get_with_auth());
47 stream->print(ESPHOME_F("}"));
48#else
49 stream->printf(R"(,{"ssid":"%s","rssi":%d,"lock":%d})", escaped_ssid, scan.get_rssi(), scan.get_with_auth());
50#endif
51 }
52 }
53 stream->print(ESPHOME_F("]}"));
54 request->send(stream);
55}
56void CaptivePortal::handle_wifisave(AsyncWebServerRequest *request) {
57 const auto &ssid = request->arg("ssid");
58 const auto &psk = request->arg("psk");
59 ESP_LOGI(TAG,
60 "Requested WiFi Settings Change:\n"
61 " SSID='%s'\n"
62 " Password=" LOG_SECRET("'%s'"),
63 ssid.c_str(), psk.c_str());
64#ifdef USE_ESP8266
65 // ESP8266 is single-threaded, call directly
66 wifi::global_wifi_component->save_wifi_sta(ssid.c_str(), psk.c_str());
67#else
68 // Defer save to main loop thread to avoid NVS operations from HTTP thread
69 this->defer([ssid, psk]() { wifi::global_wifi_component->save_wifi_sta(ssid.c_str(), psk.c_str()); });
70#endif
71 request->send(200, ESPHOME_F("text/plain"), ESPHOME_F("Saved. Connecting..."));
72}
73
75 // Disable loop by default - will be enabled when captive portal starts
76 this->disable_loop();
77}
79 this->base_->init();
80 if (!this->initialized_) {
82 }
83
85
86#if defined(USE_ESP32)
87 // Create DNS server instance for ESP-IDF
88 this->dns_server_ = make_unique<DNSServer>();
89 this->dns_server_->start(ip);
90#elif defined(USE_ARDUINO)
91 this->dns_server_ = make_unique<DNSServer>();
92 this->dns_server_->setErrorReplyCode(DNSReplyCode::NoError);
93 this->dns_server_->start(53, ESPHOME_F("*"), ip);
94#endif
95
96 this->initialized_ = true;
97 this->active_ = true;
98
99 // Enable loop() now that captive portal is active
100 this->enable_loop();
101
102 ESP_LOGV(TAG, "Captive portal started");
103}
104
105void CaptivePortal::handleRequest(AsyncWebServerRequest *req) {
106#ifdef USE_ESP32
107 char url_buf[AsyncWebServerRequest::URL_BUF_SIZE];
108 StringRef url = req->url_to(url_buf);
109#else
110 const auto &url = req->url();
111#endif
112 if (url == ESPHOME_F("/config.json")) {
113 this->handle_config(req);
114 return;
115 } else if (url == ESPHOME_F("/wifisave")) {
116 this->handle_wifisave(req);
117 return;
118 }
119
120 // All other requests get the captive portal page
121 // This includes OS captive portal detection endpoints which will trigger
122 // the captive portal when they don't receive their expected responses
123#ifndef USE_ESP8266
124 auto *response = req->beginResponse(200, ESPHOME_F("text/html"), INDEX_GZ, sizeof(INDEX_GZ));
125#else
126 auto *response = req->beginResponse_P(200, ESPHOME_F("text/html"), INDEX_GZ, sizeof(INDEX_GZ));
127#endif
128#ifdef USE_CAPTIVE_PORTAL_GZIP
129 response->addHeader(ESPHOME_F("Content-Encoding"), ESPHOME_F("gzip"));
130#else
131 response->addHeader(ESPHOME_F("Content-Encoding"), ESPHOME_F("br"));
132#endif
133 req->send(response);
134}
135
138 // Before WiFi
139 return setup_priority::WIFI + 1.0f;
140}
141void CaptivePortal::dump_config() { ESP_LOGCONFIG(TAG, "Captive Portal:"); }
142
143CaptivePortal *global_captive_portal = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
144
145} // namespace esphome::captive_portal
146
147#endif
const StringRef & get_name() const
Get the name of this Application set by pre_setup().
void enable_loop()
Enable this component's loop.
Definition component.h:248
void defer(const char *name, std::function< void()> &&f)
Defer a callback to the next loop() call with a const char* name.
void disable_loop()
Disable this component's loop.
StringRef is a reference to a string owned by something else.
Definition string_ref.h:26
constexpr const char * c_str() const
Definition string_ref.h:73
std::unique_ptr< DNSServer > dns_server_
CaptivePortal(web_server_base::WebServerBase *base)
void handle_config(AsyncWebServerRequest *request)
web_server_base::WebServerBase * base_
void handleRequest(AsyncWebServerRequest *req) override
void handle_wifisave(AsyncWebServerRequest *request)
void add_handler_without_auth(AsyncWebHandler *handler)
WARNING: Registers a handler that bypasses the USE_WEBSERVER_AUTH middleware.
Guards WiFiComponent::scan_result_.
void save_wifi_sta(const std::string &ssid, const std::string &password)
const char * json_escape_into_buffer(std::span< char > buf, StringRef value)
Copy value into buf, escaping the characters that cannot appear raw inside a JSON string literal.
Definition json_escape.h:23
CaptivePortal * global_captive_portal
constexpr float WIFI
Definition component.h:50
WiFiComponent * global_wifi_component
const char * get_mac_address_pretty_into_buffer(std::span< char, MAC_ADDRESS_PRETTY_BUFFER_SIZE > buf)
Get the device MAC address into the given buffer, in colon-separated uppercase hex notation.
Definition helpers.cpp:750
Application App
Global storage of Application pointer - only one Application can exist.
SemaphoreHandle_t lock