ESPHome 2026.11.0-dev
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"
9#include "captive_index.h"
10
12
13ESPHOME_LOG_TAG(TAG, "captive_portal");
14
15void CaptivePortal::handle_config(AsyncWebServerRequest *request) {
16 AsyncResponseStream *stream = request->beginResponseStream(ESPHOME_F("application/json"));
17 stream->addHeader(ESPHOME_F("cache-control"), ESPHOME_F("public, max-age=0, must-revalidate"));
18 char mac_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
19 const char *mac_str = get_mac_address_pretty_into_buffer(mac_s);
20#ifdef USE_ESP8266
21 stream->print(ESPHOME_F("{\"mac\":\""));
22 stream->print(mac_str);
23 stream->print(ESPHOME_F("\",\"name\":\""));
24 stream->print(App.get_name().c_str());
25 stream->print(ESPHOME_F("\",\"aps\":[{}"));
26#else
27 stream->printf(R"({"mac":"%s","name":"%s","aps":[{})", mac_str, App.get_name().c_str());
28#endif
29
30 // An SSID can contain a " or \ that would break the JSON, so escape it before writing it out. An SSID is at most
31 // 32 bytes (IEEE 802.11), so this is large enough that nothing is ever dropped. Reused for every scan result.
32 char escaped_ssid[32 * JSON_ESCAPE_MAX_EXPANSION + 1];
33 {
34 // Invariant: only bounded in-memory work under the lock; the network send
35 // happens later in request->send()
37 const auto &results = wifi::global_wifi_component->get_scan_result();
38 for (const auto &scan : results) {
39 bool with_auth = false;
40 if (!wifi::should_show_scan_entry(results, scan, with_auth))
41 continue;
42
43 json_escape_into_buffer(escaped_ssid, scan.get_ssid());
44#ifdef USE_ESP8266
45 stream->print(ESPHOME_F(",{\"ssid\":\""));
46 stream->print(escaped_ssid);
47 stream->print(ESPHOME_F("\",\"rssi\":"));
48 stream->print(scan.get_rssi());
49 stream->print(ESPHOME_F(",\"lock\":"));
50 stream->print(with_auth);
51 stream->print(ESPHOME_F("}"));
52#else
53 stream->printf(R"(,{"ssid":"%s","rssi":%d,"lock":%d})", escaped_ssid, scan.get_rssi(), with_auth);
54#endif
55 }
56 }
57 stream->print(ESPHOME_F("]}"));
58 request->send(stream);
59}
60void CaptivePortal::handle_wifisave(AsyncWebServerRequest *request) {
61 const auto &ssid = request->arg(ESPHOME_F("ssid"));
62 const auto &psk = request->arg(ESPHOME_F("psk"));
63 ESP_LOGI(TAG,
64 "Requested WiFi Settings Change:\n"
65 " SSID='%s'\n"
66 " Password=" LOG_SECRET("'%s'"),
67 ssid.c_str(), psk.c_str());
68#ifdef USE_ESP8266
69 // ESP8266 is single-threaded, call directly
70 wifi::global_wifi_component->save_wifi_sta(ssid.c_str(), psk.c_str());
71#else
72 // Defer save to main loop thread to avoid NVS operations from HTTP thread
73 this->defer([ssid, psk]() { wifi::global_wifi_component->save_wifi_sta(ssid.c_str(), psk.c_str()); });
74#endif
75 request->send(200, ESPHOME_F("text/plain"), ESPHOME_F("Saved. Connecting..."));
76}
77
79 // Disable loop by default - will be enabled when captive portal starts
80 this->disable_loop();
81}
83 // Each start takes a web server reference that end() returns once
84 if (this->active_)
85 return;
86 this->base_->init();
87 if (!this->initialized_) {
89 }
90
91 this->dns_.start(wifi::global_wifi_component->wifi_soft_ap_ip());
92
93 this->initialized_ = true;
94 this->active_ = true;
95
96 // Enable loop() now that captive portal is active
97 this->enable_loop();
98
99 ESP_LOGV(TAG, "Captive portal started");
100}
101
102void CaptivePortal::handleRequest(AsyncWebServerRequest *req) {
103#ifdef USE_ESP32
104 char url_buf[AsyncWebServerRequest::URL_BUF_SIZE];
105 StringRef url = req->url_to(url_buf);
106#else
107 const auto &url = req->url();
108#endif
109 if (url == ESPHOME_F("/config.json")) {
110 this->handle_config(req);
111 return;
112 } else if (url == ESPHOME_F("/wifisave")) {
113 this->handle_wifisave(req);
114 return;
115 }
116
117 // All other requests get the captive portal page
118 // This includes OS captive portal detection endpoints which will trigger
119 // the captive portal when they don't receive their expected responses
120 auto *response = req->beginResponse(200, ESPHOME_F("text/html"), INDEX_GZ, sizeof(INDEX_GZ));
121#ifdef USE_CAPTIVE_PORTAL_GZIP
122 response->addHeader(ESPHOME_F("Content-Encoding"), ESPHOME_F("gzip"));
123#else
124 response->addHeader(ESPHOME_F("Content-Encoding"), ESPHOME_F("br"));
125#endif
126 req->send(response);
127}
128
131 // Before WiFi
132 return setup_priority::WIFI + 1.0f;
133}
134void CaptivePortal::dump_config() { ESP_LOGCONFIG(TAG, "Captive Portal:"); }
135
136CaptivePortal *global_captive_portal = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
137
138} // namespace esphome::captive_portal
139
140#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:31
constexpr const char * c_str() const
Definition string_ref.h:78
web_server_base::CaptiveDNS dns_
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)
bool start(const network::IPAddress &ip)
Returns false when the DNS server could not start; nothing is kept, so is_running() stays false.
Definition captive_dns.h:24
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 wifi_scan_vector_t< WiFiScanResult > & get_scan_result() const
Main-loop callers may read this directly.
ESPHOME_LOG_TAG(TAG, "captive_portal")
CaptivePortal * global_captive_portal
constexpr float WIFI
Definition component.h:50
bool should_show_scan_entry(const Results &results, const Entry &scan, bool &with_auth)
Definition scan_list.h:11
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:854
const char * json_escape_into_buffer(std::span< char > buf, StringRef value, bool short_control_escapes)
Copy value into buf, escaping the characters that cannot appear raw inside a JSON string literal.
Definition helpers.cpp:432
Application App
Global storage of Application pointer - only one Application can exist.
SemaphoreHandle_t lock