Compare commits

...
Author SHA1 Message Date
J. Nick Koston 07f091059c [web_server] Match the blank page remedy to the actual cause 2026-08-19 17:23:25 -05:00
J. Nick KostonandGitHub 2807a6932b Merge branch 'dev' into web-server-offline-hint 2026-08-19 16:49:33 -05:00
J. Nick Koston ec09ce636c [web_server] Announce captive mode for explicit local: true too 2026-08-19 16:48:16 -05:00
J. Nick Koston 7f437aa680 [web_server] Surface implied behavior changes and honor manual_ip in the port warning 2026-08-19 16:09:27 -05:00
J. Nick Koston f8a60d0259 [web_server] Address review: tighter socket auto-load, flash cost in the log, fallback compile test 2026-08-19 15:26:11 -05:00
J. Nick Koston 50f50aa7e0 [web_server] Limit captive mode to port 80 and hint at the manual URL otherwise 2026-08-19 15:22:04 -05:00
J. Nick Koston 676ecae469 [wifi][web_server] Guard AP portal helpers with USE_WIFI_AP and apply review cleanups 2026-08-19 14:40:35 -05:00
J. Nick Koston 78258dc554 [wifi] Declare the AP portal helpers for builds without an access point 2026-08-19 14:30:46 -05:00
J. Nick Koston 55180938ca [web_server] Keep AUTO_LOAD static so web_server_base loads before ota.web_server 2026-08-19 14:21:17 -05:00
J. Nick Koston d88a95c3f6 [web_server] Share the captive DNS server, use the not-found fallback for probes, fold portal hooks in wifi 2026-08-19 14:15:06 -05:00
J. Nick Koston 4dad932cd8 [web_server] Self contained AP mode: embed the interface and act as captive portal 2026-08-19 14:00:43 -05:00
J. Nick Koston 3b8b90b2cd [web_server] Embed the interface and warn for AP only WiFi instead of hinting in the page 2026-08-19 13:42:52 -05:00
J. Nick Koston 9df8505c8d [web_server] Show the offline hint on a timer so a stalled download is covered too 2026-08-19 13:25:51 -05:00
J. Nick Koston 427b83dc0a [web_server] Move the AP only warning into web_server and emit the script tag once 2026-08-19 13:07:19 -05:00
J. Nick Koston deb641d413 [wifi] Warn when an AP only config serves the hosted web_server page 2026-08-19 13:02:59 -05:00
J. Nick Koston 0b3e399588 [web_server] Shorten the offline hint 2026-08-19 12:59:40 -05:00
J. Nick Koston 33d9adbef1 [web_server] Only add the offline hint without captive_portal 2026-08-19 12:57:58 -05:00
J. Nick Koston 88d6ded5f3 [web_server] Show a hint when the hosted web interface cannot be downloaded 2026-08-19 12:51:51 -05:00
22 changed files with 550 additions and 102 deletions
+2 -26
View File
@@ -3,7 +3,6 @@ import logging
import esphome.codegen as cg
from esphome.components import web_server_base, wifi
from esphome.components.web_server_base import CONF_WEB_SERVER_BASE_ID
from esphome.config_helpers import filter_source_files_from_platform
import esphome.config_validation as cv
from esphome.const import (
CONF_AP,
@@ -15,7 +14,6 @@ from esphome.const import (
PLATFORM_LN882X,
PLATFORM_RP2,
PLATFORM_RTL87XX,
PlatformFramework,
)
from esphome.core import CORE, coroutine_with_priority
from esphome.coroutine import CoroPriority
@@ -76,17 +74,7 @@ def _final_validate(config: ConfigType) -> None:
"Add 'ap:' to your WiFi configuration to enable the captive portal."
)
# Register socket needs for DNS server and additional HTTP connections
# - 1 UDP socket for DNS server
# - 3 TCP sockets for captive portal detection probes + configuration requests
# OS captive portal detection makes multiple probe requests that stay in TIME_WAIT.
# Need headroom for actual user configuration requests.
# LRU purging will reclaim idle sockets to prevent exhaustion from repeated attempts.
# The listening socket is registered by web_server_base (shared HTTP server).
from esphome.components import socket
socket.consume_sockets(3, "captive_portal")(config)
socket.consume_sockets(1, "captive_portal", socket.SocketType.UDP)(config)
web_server_base.consume_captive_dns_sockets(config, "captive_portal")
FINAL_VALIDATE_SCHEMA = _final_validate
@@ -106,16 +94,4 @@ async def to_code(config):
if config[CONF_COMPRESSION] == "gzip":
cg.add_define("USE_CAPTIVE_PORTAL_GZIP")
if CORE.using_arduino and (CORE.is_esp8266 or CORE.is_libretiny or CORE.is_rp2):
cg.add_library("DNSServer", None)
# Only compile the ESP-IDF DNS server when using ESP-IDF framework
FILTER_SOURCE_FILES = filter_source_files_from_platform(
{
"dns_server_esp32_idf.cpp": {
PlatformFramework.ESP32_ARDUINO,
PlatformFramework.ESP32_IDF,
},
}
)
web_server_base.add_captive_dns_library()
@@ -82,17 +82,7 @@ void CaptivePortal::start() {
this->base_->add_handler_without_auth(this);
}
network::IPAddress ip = wifi::global_wifi_component->wifi_soft_ap_ip();
#if defined(USE_ESP32)
// Create DNS server instance for ESP-IDF
this->dns_server_ = make_unique<DNSServer>();
this->dns_server_->start(ip);
#elif defined(USE_ARDUINO)
this->dns_server_ = make_unique<DNSServer>();
this->dns_server_->setErrorReplyCode(DNSReplyCode::NoError);
this->dns_server_->start(53, ESPHOME_F("*"), ip);
#endif
this->dns_.start(wifi::global_wifi_component->wifi_soft_ap_ip());
this->initialized_ = true;
this->active_ = true;
@@ -1,16 +1,11 @@
#pragma once
#include "esphome/core/defines.h"
#ifdef USE_CAPTIVE_PORTAL
#include <memory>
#if defined(USE_ESP32)
#include "dns_server_esp32_idf.h"
#elif defined(USE_ARDUINO)
#include <DNSServer.h>
#endif
#include "esphome/core/component.h"
#include "esphome/core/helpers.h"
#include "esphome/core/preferences.h"
#include "esphome/components/web_server_base/web_server_base.h"
#include "esphome/components/web_server_base/captive_dns.h"
namespace esphome::captive_portal {
@@ -19,17 +14,7 @@ class CaptivePortal final : public AsyncWebHandler, public Component {
CaptivePortal(web_server_base::WebServerBase *base);
void setup() override;
void dump_config() override;
void loop() override {
#if defined(USE_ESP32)
if (this->dns_server_ != nullptr) {
this->dns_server_->process_next_request();
}
#elif defined(USE_ARDUINO)
if (this->dns_server_ != nullptr) {
this->dns_server_->processNextRequest();
}
#endif
}
void loop() override { this->dns_.loop(); }
float get_setup_priority() const override;
void start();
bool is_active() const { return this->active_; }
@@ -37,10 +22,7 @@ class CaptivePortal final : public AsyncWebHandler, public Component {
this->active_ = false;
this->disable_loop(); // Stop processing DNS requests
this->base_->deinit();
if (this->dns_server_ != nullptr) {
this->dns_server_->stop();
this->dns_server_ = nullptr;
}
this->dns_.stop();
}
bool canHandle(AsyncWebServerRequest *request) const override {
@@ -60,9 +42,7 @@ class CaptivePortal final : public AsyncWebHandler, public Component {
web_server_base::WebServerBase *base_;
bool initialized_{false};
bool active_{false};
#if defined(USE_ARDUINO) || defined(USE_ESP32)
std::unique_ptr<DNSServer> dns_server_{nullptr};
#endif
web_server_base::CaptiveDNS dns_;
};
extern CaptivePortal *global_captive_portal; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
+116 -5
View File
@@ -11,6 +11,7 @@ from esphome.components.logger import request_log_listener
from esphome.components.web_server_base import CONF_WEB_SERVER_BASE_ID
import esphome.config_validation as cv
from esphome.const import (
CONF_AP,
CONF_AUTH,
CONF_COMPRESSION,
CONF_CSS_INCLUDE,
@@ -22,15 +23,19 @@ from esphome.const import (
CONF_JS_URL,
CONF_LOCAL,
CONF_LOG,
CONF_MANUAL_IP,
CONF_NAME,
CONF_NETWORKS,
CONF_OTA,
CONF_PASSWORD,
CONF_PORT,
CONF_STATIC_IP,
CONF_TYPE,
CONF_USERNAME,
CONF_VERSION,
CONF_WEB_SERVER,
CONF_WEB_SERVER_ID,
CONF_WIFI,
PLATFORM_BK72XX,
PLATFORM_ESP32,
PLATFORM_ESP8266,
@@ -44,7 +49,23 @@ from esphome.types import ConfigType
_LOGGER = logging.getLogger(__name__)
AUTO_LOAD = ["json", "web_server_base"]
def AUTO_LOAD() -> list[str]:
# No config parameter on purpose: that would make this a late (dynamic) auto-load and
# ota.web_server's dependency on web_server_base would not be satisfied in time.
auto_load = ["json", "web_server_base"]
# The AP mode DNS server (web_server_base/dns_server_esp32_idf) uses socket; only
# configs with a WiFi access point can end up in AP mode. CORE.raw_config is set
# after package merging, so a wifi block from a package is visible here.
wifi = CORE.raw_config.get(CONF_WIFI) if CORE.raw_config else None
if (
CORE.is_esp32
and wifi is not None
and (not isinstance(wifi, dict) or CONF_AP in wifi)
):
auto_load.append("socket")
return auto_load
AUTH_TYPE_BASIC = "basic"
AUTH_TYPE_DIGEST = "digest"
@@ -203,9 +224,6 @@ def _final_validate_sorting(config: ConfigType) -> None:
)
FINAL_VALIDATE_SCHEMA = _final_validate_sorting
def _consume_web_server_sockets(config: ConfigType) -> ConfigType:
"""Register socket needs for web_server component."""
from esphome.components import socket
@@ -332,6 +350,95 @@ async def add_entity_config(entity, config):
)
def wifi_is_ap_only(wifi_config: ConfigType | None) -> bool:
"""AP only: an access point and no network to join, so the device is only ever reached
through its own AP."""
return (
wifi_config is not None
and CONF_AP in wifi_config
and not wifi_config.get(CONF_NETWORKS)
)
def serve_local(config: ConfigType, wifi_config: ConfigType | None) -> bool:
"""Embed the interface unless ``local:`` says otherwise; AP only WiFi has no internet
for the hosted page. Version 1 has no local mode."""
if (local := config.get(CONF_LOCAL)) is not None:
return local
return config[CONF_VERSION] != 1 and wifi_is_ap_only(wifi_config)
def serve_captive(config: ConfigType, full_config: ConfigType) -> bool:
"""web_server runs its own captive portal while the AP is up: embedded interface plus
an access point, unless captive_portal (which owns that role) is configured. Only on
port 80: the OS captive portal probes and the DHCP portal URI always use port 80, so
a portal on another port could never be discovered."""
wifi_config = full_config.get(CONF_WIFI)
return (
"captive_portal" not in full_config
and config[CONF_PORT] == 80
and wifi_config is not None
and CONF_AP in wifi_config
and serve_local(config, wifi_config)
)
def _final_validate_ap_mode(config: ConfigType) -> None:
full_config = fv.full_config.get()
wifi_config = full_config.get(CONF_WIFI)
captive = serve_captive(config, full_config)
local = serve_local(config, wifi_config)
if captive:
web_server_base.consume_captive_dns_sockets(config, "web_server")
# Surface behavior that the config does not spell out.
if local and CONF_LOCAL not in config:
_LOGGER.info(
"WiFi is AP only: embedding the web interface in the firmware "
"(local: true, roughly 13 KB of flash for version 2, 78 KB for version 3)%s. "
"Set 'local: false' to load it from the internet instead.",
" and serving it as a captive portal on the access point"
if captive
else "",
)
elif captive:
_LOGGER.info(
"web_server will act as a captive portal while the %saccess point is active.",
"" if wifi_is_ap_only(wifi_config) else "fallback ",
)
if not wifi_is_ap_only(wifi_config):
return
if not local:
_LOGGER.warning(
"WiFi is AP only and the web_server interface is loaded from the internet, "
"which browsers on the access point usually cannot reach; the page stays "
"blank. %s so the interface is embedded in the firmware.",
"Remove 'local: false'"
if config.get(CONF_LOCAL) is False
else "Migrate to version 2 or 3",
)
elif config[CONF_PORT] != 80:
ap_ip = "192.168.4.1"
if (manual_ip := wifi_config[CONF_AP].get(CONF_MANUAL_IP)) is not None:
ap_ip = str(manual_ip[CONF_STATIC_IP])
_LOGGER.warning(
"WiFi is AP only and web_server uses port %d. The interface cannot open "
"automatically on the access point (captive portal detection only works on "
"port 80); open http://%s:%d/ manually, or remove 'port:' to use 80.",
config[CONF_PORT],
ap_ip,
config[CONF_PORT],
)
def _final_validate(config: ConfigType) -> None:
# Called one after the other rather than via cv.All: these return None.
_final_validate_sorting(config)
_final_validate_ap_mode(config)
FINAL_VALIDATE_SCHEMA = _final_validate
def build_index_html(config) -> str:
html = "<!DOCTYPE html><html><head><meta charset=UTF-8><link rel=icon href=data:>"
css_include = config.get(CONF_CSS_INCLUDE)
@@ -432,8 +539,12 @@ async def to_code(config):
with path.open(encoding="utf-8") as js_file:
add_resource_as_progmem("JS_INCLUDE", js_file.read())
cg.add(var.set_include_internal(config[CONF_INCLUDE_INTERNAL]))
if CONF_LOCAL in config and config[CONF_LOCAL]:
if serve_local(config, CORE.config.get(CONF_WIFI)):
cg.add_define("USE_WEBSERVER_LOCAL")
if serve_captive(config, CORE.config):
# AP mode: DNS server plus redirect of unknown URLs so phones open the interface
cg.add_define("USE_WEBSERVER_CAPTIVE")
web_server_base.add_captive_dns_library()
if config[CONF_COMPRESSION] == "gzip":
cg.add_define("USE_WEBSERVER_GZIP")
+56 -3
View File
@@ -44,6 +44,10 @@
#include "esphome/components/radio_frequency/radio_frequency.h"
#endif
#ifdef USE_WEBSERVER_CAPTIVE
#include "esphome/components/wifi/wifi_component.h"
#endif
#ifdef USE_WEBSERVER_LOCAL
#if USE_WEBSERVER_VERSION == 2
#include "server_index_v2.h"
@@ -340,7 +344,15 @@ void DeferredUpdateEventSourceList::on_client_disconnect_(DeferredUpdateEventSou
}
#endif
WebServer::WebServer(web_server_base::WebServerBase *base) : base_(base) {}
#ifdef USE_WEBSERVER_CAPTIVE
WebServer *global_web_server = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
#endif
WebServer::WebServer(web_server_base::WebServerBase *base) : base_(base) {
#ifdef USE_WEBSERVER_CAPTIVE
global_web_server = this;
#endif
}
#ifdef USE_WEBSERVER_CSS_INCLUDE
void WebServer::set_css_include(const char *css_include) { this->css_include_ = css_include; }
@@ -386,6 +398,11 @@ void WebServer::setup() {
this->base_->add_handler(&this->events_);
#endif
this->base_->add_handler(this);
#ifdef USE_WEBSERVER_CAPTIVE
// Not-found fallback (outside the auth middleware): the OS captive portal probes hit
// arbitrary URLs and must get the redirect without credentials.
this->base_->get_server()->onNotFound([this](AsyncWebServerRequest *request) { this->handle_not_found_(request); });
#endif
// OTA is now handled by the web_server OTA platform
@@ -401,16 +418,52 @@ void WebServer::setup() {
});
}
void WebServer::loop() {
// No SSE clients connected; stop looping until a new client connects via
bool keep_looping = this->events_.loop();
#ifdef USE_WEBSERVER_CAPTIVE
this->dns_.loop();
keep_looping |= this->dns_.is_running();
#endif
// No SSE clients connected (and no captive DNS to serve); stop looping until a new client connects via
// enable_loop_soon_any_context(). This is safe because:
// - set_interval/set_timeout/defer run via the Scheduler, independent of loop()
// - deferrable_send_state early-outs when no clients are connected
// - try_send_nodefer (log, ping) iterates sessions which are empty
// - REST API handlers use defer() which runs via the Scheduler
if (!this->events_.loop())
if (!keep_looping)
this->disable_loop();
}
#ifdef USE_WEBSERVER_CAPTIVE
void WebServer::start_captive() {
// CaptiveDNS::start() no-ops too; this guard just avoids repeating the log and enable_loop
if (this->dns_.is_running())
return;
network::IPAddress ip = wifi::global_wifi_component->wifi_soft_ap_ip();
this->dns_.start(ip);
this->enable_loop();
char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
ESP_LOGI(TAG, "AP mode: serving the web interface as captive portal at http://%s/", ip.str_to(ip_buf));
}
void WebServer::end_captive() { this->dns_.stop(); }
void WebServer::handle_not_found_(AsyncWebServerRequest *request) {
// OS captive portal probe (or any other unknown page) while the AP is up: send the browser
// to the real page. A redirect rather than the page itself, because the interface resolves
// its /events and REST paths relative to the page URL.
if (this->dns_.is_running() && request->method() == HTTP_GET) {
// Captive mode requires port 80 (enforced at validation), so no port suffix is needed.
char location[7 + network::IP_ADDRESS_BUFFER_SIZE + 1];
size_t pos = buf_append_str(location, sizeof(location), 0, "http://");
wifi::global_wifi_component->wifi_soft_ap_ip().str_to(location + pos);
buf_append_str(location, sizeof(location), strlen(location), "/");
request->redirect(location);
return;
}
request->send(404);
}
#endif
#ifdef USE_LOGGER
void WebServer::on_log(uint8_t level, const char *tag, const char *message, size_t message_len) {
(void) level;
@@ -4,6 +4,9 @@
#include "esphome/components/json/json_util.h"
#include "esphome/components/web_server_base/web_server_base.h"
#ifdef USE_WEBSERVER_CAPTIVE
#include "esphome/components/web_server_base/captive_dns.h"
#endif
#ifdef USE_WEBSERVER
#include "esphome/core/component.h"
#include "esphome/core/controller.h"
@@ -276,6 +279,18 @@ class WebServer final : public Controller, public Component, public AsyncWebHand
/// Handle an index request under '/'.
void handle_index_request(AsyncWebServerRequest *request);
#ifdef USE_WEBSERVER_CAPTIVE
/** AP mode: run a DNS server that answers every name with the AP address and redirect any
* unknown URL to the interface, so a phone joining the AP opens it through the OS captive
* portal check. Started and ended by the wifi component with the access point. start may run
* before setup() (wifi sets up first): safe because enable_loop() is a no-op before setup;
* nothing but the DNS server may be touched, in particular not base_ or the handlers.
*/
void start_captive();
void end_captive();
bool is_captive() const { return this->dns_.is_running(); }
#endif
/// Return the webserver configuration as JSON.
json::SerializationBuffer<> get_config_json();
@@ -597,6 +612,10 @@ class WebServer final : public Controller, public Component, public AsyncWebHand
#elif USE_ARDUINO
DeferredUpdateEventSourceList events_;
#endif
#ifdef USE_WEBSERVER_CAPTIVE
void handle_not_found_(AsyncWebServerRequest *request);
web_server_base::CaptiveDNS dns_;
#endif
#if USE_WEBSERVER_VERSION == 1
const char *css_url_{nullptr};
@@ -696,5 +715,9 @@ class WebServer final : public Controller, public Component, public AsyncWebHand
#endif
};
#ifdef USE_WEBSERVER_CAPTIVE
extern WebServer *global_web_server; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
#endif
} // namespace esphome::web_server
#endif
+31 -1
View File
@@ -1,11 +1,13 @@
from pathlib import Path
import esphome.codegen as cg
from esphome.config_helpers import filter_source_files_from_platform
import esphome.config_validation as cv
from esphome.const import CONF_ID
from esphome.const import CONF_ID, PlatformFramework
from esphome.core import CORE, coroutine_with_priority
from esphome.coroutine import CoroPriority
from esphome.helpers import copy_file_if_changed
from esphome.types import ConfigType
CODEOWNERS = ["@esphome/core"]
DEPENDENCIES = ["network"]
@@ -25,6 +27,22 @@ WebServerBase = web_server_base_ns.class_("WebServerBase")
CONF_WEB_SERVER_BASE_ID = "web_server_base_id"
def consume_captive_dns_sockets(config: ConfigType, name: str) -> None:
"""Register the sockets a captive portal needs on top of the shared HTTP server:
1 UDP socket for the DNS server and 3 TCP sockets for the OS captive portal probes,
which make several requests that linger in TIME_WAIT."""
from esphome.components import socket
socket.consume_sockets(3, name)(config)
socket.consume_sockets(1, name, socket.SocketType.UDP)(config)
def add_captive_dns_library() -> None:
"""Pull in the Arduino DNSServer library used by CaptiveDNS off ESP32."""
if CORE.using_arduino and (CORE.is_esp8266 or CORE.is_libretiny or CORE.is_rp2):
cg.add_library("DNSServer", None)
def _consume_web_server_base_sockets(config):
"""Register the shared listening socket for the HTTP server.
@@ -80,3 +98,15 @@ async def to_code(config):
cg.add_platformio_option("extra_scripts", ["pre:fix_rp2040_hash.py"])
# https://github.com/ESP32Async/ESPAsyncWebServer/blob/main/library.json
cg.add_library("ESP32Async/ESPAsyncWebServer", "3.9.6")
# The DNS server used for captive portals on ESP32; other platforms use the Arduino
# DNSServer library. Its source is also guarded by USE_CAPTIVE_PORTAL / USE_WEBSERVER_CAPTIVE.
FILTER_SOURCE_FILES = filter_source_files_from_platform(
{
"dns_server_esp32_idf.cpp": {
PlatformFramework.ESP32_ARDUINO,
PlatformFramework.ESP32_IDF,
},
}
)
@@ -0,0 +1,58 @@
#pragma once
#include "esphome/core/defines.h"
// DNS server that answers every name with the access point address, so a phone joining the
// AP runs its captive portal check against the device. Shared by captive_portal and the
// web_server AP mode; hides the ESP32 (own implementation) vs Arduino (DNSServer library) split.
#if defined(USE_CAPTIVE_PORTAL) || defined(USE_WEBSERVER_CAPTIVE)
#include <memory>
#include "esphome/components/network/ip_address.h"
#include "esphome/core/helpers.h"
#include "esphome/core/progmem.h"
#if defined(USE_ESP32)
#include "dns_server_esp32_idf.h"
#elif defined(USE_ARDUINO)
#include <DNSServer.h>
#endif
namespace esphome::web_server_base {
// The server object only exists while running, so an idle owner (AP not up) pays one pointer.
class CaptiveDNS {
public:
void start(const network::IPAddress &ip) {
if (this->dns_server_ != nullptr)
return;
this->dns_server_ = make_unique<DNSServer>();
#if defined(USE_ESP32)
this->dns_server_->start(ip);
#elif defined(USE_ARDUINO)
this->dns_server_->setErrorReplyCode(DNSReplyCode::NoError);
this->dns_server_->start(53, ESPHOME_F("*"), ip);
#endif
}
void stop() {
if (this->dns_server_ == nullptr)
return;
this->dns_server_->stop();
this->dns_server_ = nullptr;
}
/// Answer one pending query; call from the owner's loop() while running.
void loop() {
if (this->dns_server_ == nullptr)
return;
#if defined(USE_ESP32)
this->dns_server_->process_next_request();
#elif defined(USE_ARDUINO)
this->dns_server_->processNextRequest();
#endif
}
bool is_running() const { return this->dns_server_ != nullptr; }
protected:
// ESP32: web_server_base::DNSServer from dns_server_esp32_idf.h; Arduino: the library class.
std::unique_ptr<DNSServer> dns_server_;
};
} // namespace esphome::web_server_base
#endif // USE_CAPTIVE_PORTAL || USE_WEBSERVER_CAPTIVE
@@ -1,5 +1,5 @@
#include "dns_server_esp32_idf.h"
#ifdef USE_ESP32
#if defined(USE_ESP32) && (defined(USE_CAPTIVE_PORTAL) || defined(USE_WEBSERVER_CAPTIVE))
#include "esphome/core/log.h"
#include "esphome/core/hal.h"
@@ -7,9 +7,9 @@
#include <lwip/sockets.h>
#include <lwip/inet.h>
namespace esphome::captive_portal {
namespace esphome::web_server_base {
static const char *const TAG = "captive_portal.dns";
static const char *const TAG = "web_server_base.dns";
// DNS constants
static constexpr uint16_t DNS_PORT = 53;
@@ -202,6 +202,6 @@ void DNSServer::process_next_request() {
}
}
} // namespace esphome::captive_portal
} // namespace esphome::web_server_base
#endif // USE_ESP32
#endif // USE_ESP32 && (USE_CAPTIVE_PORTAL || USE_WEBSERVER_CAPTIVE)
@@ -1,11 +1,15 @@
#pragma once
#ifdef USE_ESP32
#include "esphome/core/defines.h"
// Small DNS server that answers every query with the access point address, so a
// phone joining the AP opens the captive portal or web_server page on its own.
// Shared by captive_portal and the web_server AP mode.
#if defined(USE_ESP32) && (defined(USE_CAPTIVE_PORTAL) || defined(USE_WEBSERVER_CAPTIVE))
#include "esphome/core/helpers.h"
#include "esphome/components/network/ip_address.h"
#include "esphome/components/socket/socket.h"
namespace esphome::captive_portal {
namespace esphome::web_server_base {
class DNSServer {
public:
@@ -27,6 +31,6 @@ class DNSServer {
uint8_t buffer_[DNS_BUFFER_SIZE];
};
} // namespace esphome::captive_portal
} // namespace esphome::web_server_base
#endif // USE_ESP32
#endif // USE_ESP32 && (USE_CAPTIVE_PORTAL || USE_WEBSERVER_CAPTIVE)
@@ -325,9 +325,9 @@ StringRef AsyncWebServerRequest::url_to(std::span<char, URL_BUF_SIZE> buffer) co
return StringRef(buffer.data(), decoded_len);
}
void AsyncWebServerRequest::redirect(const std::string &url) {
void AsyncWebServerRequest::redirect(const char *url) {
httpd_resp_set_status(*this, "302 Found");
httpd_resp_set_hdr(*this, "Location", url.c_str());
httpd_resp_set_hdr(*this, "Location", url);
httpd_resp_set_hdr(*this, "Connection", "close");
httpd_resp_send(*this, nullptr, 0);
}
@@ -132,7 +132,8 @@ class AsyncWebServerRequest {
void requestAuthentication() const;
#endif
void redirect(const std::string &url);
void redirect(const char *url);
void redirect(const std::string &url) { this->redirect(url.c_str()); }
inline void ESPHOME_ALWAYS_INLINE send(AsyncWebServerResponse *response) {
httpd_resp_send(*this, response->get_content_data(), response->get_content_size());
+47 -16
View File
@@ -36,6 +36,9 @@
#ifdef USE_CAPTIVE_PORTAL
#include "esphome/components/captive_portal/captive_portal.h"
#endif
#ifdef USE_WEBSERVER_CAPTIVE
#include "esphome/components/web_server/web_server.h"
#endif
#ifdef USE_IMPROV
#include "esphome/components/esp32_improv/esp32_improv_component.h"
@@ -728,9 +731,9 @@ void WiFiComponent::start() {
if (captive_portal::global_captive_portal != nullptr) {
this->wifi_sta_pre_setup_();
this->start_scanning();
captive_portal::global_captive_portal->start();
}
#endif
this->start_ap_portal_();
#endif // USE_WIFI_AP
}
#ifdef USE_IMPROV
@@ -791,8 +794,8 @@ void WiFiComponent::loop() {
this->check_connecting_finished(now);
break;
}
// Use longer cooldown when captive portal/improv is active to avoid disrupting user config
bool portal_active = this->is_captive_portal_active_() || this->is_esp32_improv_active_();
// Use longer cooldown when a portal/improv is active to avoid disrupting a user on the AP
bool portal_active = this->is_ap_portal_active_() || this->is_esp32_improv_active_();
uint32_t cooldown_duration = portal_active ? WIFI_COOLDOWN_WITH_AP_ACTIVE_MS : WIFI_COOLDOWN_DURATION_MS;
if (now - this->action_started_ > cooldown_duration) {
// After cooldown we either restarted the adapter because of
@@ -861,13 +864,11 @@ void WiFiComponent::loop() {
ESP_LOGI(TAG, "Starting fallback AP");
this->setup_ap_config_();
#ifdef USE_CAPTIVE_PORTAL
if (captive_portal::global_captive_portal != nullptr) {
// Reset so we force one full scan after captive portal starts
// (previous scans were filtered because captive portal wasn't active yet)
this->has_completed_scan_after_captive_portal_start_ = false;
captive_portal::global_captive_portal->start();
}
// Reset so we force one full scan after captive portal starts
// (previous scans were filtered because captive portal wasn't active yet)
this->has_completed_scan_after_captive_portal_start_ = false;
#endif
this->start_ap_portal_();
}
}
#endif // USE_WIFI_AP
@@ -1618,10 +1619,8 @@ void WiFiComponent::check_connecting_finished(uint32_t now) {
this->retry_phase_ = WiFiRetryPhase::INITIAL_CONNECT;
this->num_retried_ = 0;
if (this->has_ap()) {
#ifdef USE_CAPTIVE_PORTAL
if (this->is_captive_portal_active_()) {
captive_portal::global_captive_portal->end();
}
#ifdef USE_WIFI_AP
this->end_ap_portal_();
#endif
ESP_LOGD(TAG, "Disabling AP");
this->wifi_mode_({}, false);
@@ -1948,10 +1947,10 @@ bool WiFiComponent::transition_to_phase_(WiFiRetryPhase new_phase) {
break;
case WiFiRetryPhase::RESTARTING_ADAPTER:
// Skip actual adapter restart if captive portal/improv is active
// Skip actual adapter restart if a portal/improv is active
// This allows state machine to reset num_retried_ and trigger fresh scan
// without disrupting the captive portal/improv connection
if (!this->is_captive_portal_active_() && !this->is_esp32_improv_active_()) {
// without disrupting the portal/improv connection
if (!this->is_ap_portal_active_() && !this->is_esp32_improv_active_()) {
this->restart_adapter();
} else {
// Even when skipping full restart, disconnect to clear driver state
@@ -2213,6 +2212,38 @@ bool WiFiComponent::is_captive_portal_active_() {
return false;
#endif
}
bool WiFiComponent::is_ap_portal_active_() {
#ifdef USE_WEBSERVER_CAPTIVE
if (web_server::global_web_server->is_captive())
return true;
#endif
return this->is_captive_portal_active_();
}
#ifdef USE_WIFI_AP
// global_web_server needs no null check: codegen always instantiates WebServer when
// USE_WEBSERVER_CAPTIVE is defined, and the constructor assigns the global.
void WiFiComponent::start_ap_portal_() {
#ifdef USE_CAPTIVE_PORTAL
if (captive_portal::global_captive_portal != nullptr)
captive_portal::global_captive_portal->start();
#endif
#ifdef USE_WEBSERVER_CAPTIVE
web_server::global_web_server->start_captive();
#endif
}
void WiFiComponent::end_ap_portal_() {
#ifdef USE_CAPTIVE_PORTAL
if (this->is_captive_portal_active_())
captive_portal::global_captive_portal->end();
#endif
#ifdef USE_WEBSERVER_CAPTIVE
web_server::global_web_server->end_captive();
#endif
}
#endif // USE_WIFI_AP
bool WiFiComponent::is_esp32_improv_active_() {
#ifdef USE_IMPROV
return esp32_improv::global_improv_component != nullptr && esp32_improv::global_improv_component->is_active();
+6
View File
@@ -789,6 +789,12 @@ class WiFiComponent final : public Component {
network::IPAddress wifi_dns_ip_(int num);
bool is_captive_portal_active_();
/// captive_portal or the web_server AP mode is serving a user on the access point
bool is_ap_portal_active_();
#ifdef USE_WIFI_AP
void start_ap_portal_();
void end_ap_portal_();
#endif
bool is_esp32_improv_active_();
#ifdef USE_WIFI_FAST_CONNECT
@@ -1128,10 +1128,16 @@ bool WiFiComponent::wifi_ap_ip_config_(const optional<ManualIP> &manual_ip) {
return false;
}
#if defined(USE_CAPTIVE_PORTAL) && ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 0)
// Configure DHCP Option 114 (Captive Portal URI) if captive portal is enabled
// This provides a standards-compliant way for clients to discover the captive portal
if (captive_portal::global_captive_portal != nullptr) {
#if (defined(USE_CAPTIVE_PORTAL) || defined(USE_WEBSERVER_CAPTIVE)) && ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 0)
// Configure DHCP Option 114 (Captive Portal URI) if captive portal or the web_server AP
// mode is enabled. This provides a standards-compliant way for clients to discover the portal
#ifdef USE_WEBSERVER_CAPTIVE
// web_server AP mode always serves the portal when compiled in
const bool has_portal = true;
#else
const bool has_portal = captive_portal::global_captive_portal != nullptr;
#endif
if (has_portal) {
// Buffer must be static - dhcps_set_option_info stores pointer, doesn't copy
static char captive_portal_uri[24]; // "http://" (7) + IPv4 max (15) + null
memcpy(captive_portal_uri, "http://", 7); // NOLINT(bugprone-not-null-terminated-result) - str_to null-terminates
+3
View File
@@ -353,6 +353,7 @@
#define USE_WEBSERVER
#define USE_WEBSERVER_AUTH
#define USE_WEBSERVER_AUTH_DIGEST
#define USE_WEBSERVER_CAPTIVE
#define USE_WEBSERVER_OTA
#define USE_WEBSERVER_PORT 80 // NOLINT
#define USE_WEBSERVER_GZIP
@@ -466,6 +467,7 @@
#define USE_WEBSERVER
#define USE_WEBSERVER_AUTH
#define USE_WEBSERVER_AUTH_DIGEST
#define USE_WEBSERVER_CAPTIVE
#define USE_WEBSERVER_PORT 80 // NOLINT
#endif
@@ -523,6 +525,7 @@
#define USE_WEBSERVER
#define USE_WEBSERVER_AUTH
#define USE_WEBSERVER_AUTH_DIGEST
#define USE_WEBSERVER_CAPTIVE
#define USE_WEBSERVER_PORT 80 // NOLINT
#define USE_ESPHOME_TASK_LOG_BUFFER
#define ESPHOME_TASK_LOG_BUFFER_SIZE 768
@@ -0,0 +1,11 @@
# STA with AP fallback plus local: true opts the fallback into captive AP mode; exercises
# the runtime start (fallback branch in wifi loop) and end (on STA connect) paths.
wifi:
ssid: MySSID
password: password1
ap:
ssid: "ESPHome-Test"
password: "Test1234!"
web_server:
local: true
@@ -0,0 +1,9 @@
# AP mode: with a WiFi access point and the interface embedded in the firmware, web_server
# runs its own captive portal (DNS server, unknown URLs redirect to the page).
wifi:
ap:
ssid: "ESPHome-Test"
password: "Test1234!"
web_server:
local: true
@@ -0,0 +1,2 @@
packages:
web_server: !include common-ap-fallback.yaml
@@ -0,0 +1,2 @@
packages:
web_server: !include common-ap-mode.yaml
@@ -0,0 +1,2 @@
packages:
web_server: !include common-ap-mode.yaml
@@ -0,0 +1,150 @@
"""Tests for the web_server AP mode helpers."""
import logging
import pytest
from esphome.components.web_server import (
_final_validate_ap_mode,
serve_captive,
serve_local,
)
from esphome.const import (
CONF_AP,
CONF_LOCAL,
CONF_NETWORKS,
CONF_PORT,
CONF_SSID,
CONF_VERSION,
CONF_WIFI,
)
import esphome.final_validate as fv
AP_ONLY = {CONF_AP: {}}
AP_FALLBACK = {CONF_AP: {}, CONF_NETWORKS: [{CONF_SSID: "x"}]}
STA_ONLY = {CONF_NETWORKS: [{CONF_SSID: "x"}]}
@pytest.mark.parametrize(
("web_server_config", "wifi_config", "expected"),
[
# AP only: embed the interface, the AP has no internet.
({CONF_VERSION: 2}, AP_ONLY, True),
({CONF_VERSION: 3}, AP_ONLY, True),
# Explicit setting always wins.
({CONF_VERSION: 2, CONF_LOCAL: False}, AP_ONLY, False),
({CONF_VERSION: 2, CONF_LOCAL: True}, STA_ONLY, True),
# AP fallback, no AP, no wifi, or version 1 (no local mode): hosted page.
({CONF_VERSION: 2}, AP_FALLBACK, False),
({CONF_VERSION: 2}, STA_ONLY, False),
({CONF_VERSION: 2}, None, False),
({CONF_VERSION: 1}, AP_ONLY, False),
],
)
def test_serve_local(
web_server_config: dict, wifi_config: dict | None, expected: bool
) -> None:
"""The interface is embedded for AP only WiFi unless local is set explicitly."""
assert serve_local(web_server_config, wifi_config) is expected
@pytest.mark.parametrize(
("web_server_config", "full_config", "expected"),
[
# AP only: local is implied, web_server is the captive portal.
({CONF_VERSION: 2}, {CONF_WIFI: AP_ONLY}, True),
# Captive portal probes only work on port 80.
({CONF_VERSION: 2, CONF_PORT: 8080}, {CONF_WIFI: AP_ONLY}, False),
# AP fallback needs an explicit local: true to be captive.
({CONF_VERSION: 2}, {CONF_WIFI: AP_FALLBACK}, False),
({CONF_VERSION: 2, CONF_LOCAL: True}, {CONF_WIFI: AP_FALLBACK}, True),
# captive_portal owns the role when configured.
({CONF_VERSION: 2}, {CONF_WIFI: AP_ONLY, "captive_portal": {}}, False),
# No AP, no wifi, hosted page, or version 1: never captive.
({CONF_VERSION: 2, CONF_LOCAL: True}, {CONF_WIFI: STA_ONLY}, False),
({CONF_VERSION: 2, CONF_LOCAL: True}, {}, False),
({CONF_VERSION: 2, CONF_LOCAL: False}, {CONF_WIFI: AP_ONLY}, False),
({CONF_VERSION: 1}, {CONF_WIFI: AP_ONLY}, False),
],
)
def test_serve_captive(
web_server_config: dict, full_config: dict, expected: bool
) -> None:
web_server_config.setdefault(CONF_PORT, 80)
assert serve_captive(web_server_config, full_config) is expected
@pytest.mark.parametrize(
("web_server_config", "expect_warning"),
[
# Explicit local: false on an AP only device: the hosted page will stay blank.
({CONF_VERSION: 2, CONF_PORT: 80, CONF_LOCAL: False}, True),
# Default: embedded and captive, nothing to warn about.
({CONF_VERSION: 2, CONF_PORT: 80}, False),
],
)
def test_final_validate_ap_mode_warns_for_hosted_page(
web_server_config: dict, expect_warning: bool, caplog: pytest.LogCaptureFixture
) -> None:
token = fv.full_config.set({"web_server": web_server_config, CONF_WIFI: AP_ONLY})
try:
with caplog.at_level(logging.WARNING):
_final_validate_ap_mode(web_server_config)
finally:
fv.full_config.reset(token)
assert ("stays blank" in caplog.text) is expect_warning
def test_final_validate_ap_mode_warns_for_non_default_port(
caplog: pytest.LogCaptureFixture,
) -> None:
"""Captive portal detection needs port 80; other ports get a hint, not captive mode."""
config = {CONF_VERSION: 2, CONF_PORT: 8080}
token = fv.full_config.set({"web_server": config, CONF_WIFI: AP_ONLY})
try:
with caplog.at_level(logging.WARNING):
_final_validate_ap_mode(config)
finally:
fv.full_config.reset(token)
assert "cannot open automatically" in caplog.text
assert "http://192.168.4.1:8080/" in caplog.text
def test_final_validate_ap_mode_port_warning_uses_manual_ip(
caplog: pytest.LogCaptureFixture,
) -> None:
"""The manual URL in the port warning honors wifi.ap.manual_ip."""
from esphome.const import CONF_MANUAL_IP, CONF_STATIC_IP
config = {CONF_VERSION: 2, CONF_PORT: 8080}
wifi = {CONF_AP: {CONF_MANUAL_IP: {CONF_STATIC_IP: "10.0.0.1"}}}
token = fv.full_config.set({"web_server": config, CONF_WIFI: wifi})
try:
with caplog.at_level(logging.WARNING):
_final_validate_ap_mode(config)
finally:
fv.full_config.reset(token)
assert "http://10.0.0.1:8080/" in caplog.text
@pytest.mark.parametrize(
("wifi_config", "expected"),
[
# Explicit local: true on a fallback AP: announce the captive fallback role.
(AP_FALLBACK, "fallback access point"),
# Explicit local: true on AP only skips the implied-local info; still announce.
(AP_ONLY, "captive portal while the access point"),
],
)
def test_final_validate_ap_mode_informs_explicit_local_captive(
wifi_config: dict, expected: str, caplog: pytest.LogCaptureFixture
) -> None:
"""Explicit local: true logs that web_server becomes the captive portal."""
config = {CONF_VERSION: 2, CONF_PORT: 80, CONF_LOCAL: True}
token = fv.full_config.set({"web_server": config, CONF_WIFI: wifi_config})
try:
with caplog.at_level(logging.INFO):
_final_validate_ap_mode(config)
finally:
fv.full_config.reset(token)
assert expected in caplog.text