ESPHome 2026.8.2
Loading...
Searching...
No Matches
web_server.cpp
Go to the documentation of this file.
1#include "web_server.h"
2#ifdef USE_WEBSERVER
11#include "esphome/core/log.h"
12#include "esphome/core/util.h"
13
14#if !defined(USE_ESP32) && defined(USE_ARDUINO)
15#include "StreamString.h"
16#endif
17
18#include <cstdlib>
19
20#ifdef USE_LIGHT
22#endif
23
24#ifdef USE_LOGGER
26#endif
27
28#ifdef USE_CLIMATE
30#endif
31
32#ifdef USE_UPDATE
34#endif
35
36#ifdef USE_WATER_HEATER
38#endif
39
40#ifdef USE_INFRARED
42#endif
43#ifdef USE_RADIO_FREQUENCY
45#endif
46
47#ifdef USE_WEBSERVER_LOCAL
48#if USE_WEBSERVER_VERSION == 2
49#include "server_index_v2.h"
50#elif USE_WEBSERVER_VERSION == 3
51#include "server_index_v3.h"
52#endif
53#endif
54
55namespace esphome::web_server {
56
57static const char *const TAG = "web_server";
58
59// View a state LogString as a ProgmemStr so ArduinoJson serializes it PROGMEM-aware on ESP8266.
60[[maybe_unused]] static ProgmemStr json_state_str(const LogString *s) { return reinterpret_cast<ProgmemStr>(s); }
61
62// Parse URL and return match info
63// URL formats (disambiguated by HTTP method for 3-segment case):
64// GET /{domain}/{entity_name} - main device state
65// POST /{domain}/{entity_name}/{action} - main device action
66// GET /{domain}/{device_name}/{entity_name} - sub-device state (USE_DEVICES only)
67// POST /{domain}/{device_name}/{entity_name}/{action} - sub-device action (USE_DEVICES only)
68static UrlMatch match_url(const char *url_ptr, size_t url_len, bool only_domain, bool is_post = false) {
69 // URL must start with '/' and have content after it
70 if (url_len < 2 || url_ptr[0] != '/')
71 return UrlMatch{};
72
73 const char *p = url_ptr + 1;
74 const char *end = url_ptr + url_len;
75
76 // Helper to find next segment: returns pointer after '/' or nullptr if no more slashes
77 auto next_segment = [&end](const char *start) -> const char * {
78 const char *slash = (const char *) memchr(start, '/', end - start);
79 return slash ? slash + 1 : nullptr;
80 };
81
82 // Helper to make StringRef from segment start to next segment (or end)
83 auto make_ref = [&end](const char *start, const char *next_start) -> StringRef {
84 return StringRef(start, (next_start ? next_start - 1 : end) - start);
85 };
86
87 // Parse domain segment
88 const char *s1 = p;
89 const char *s2 = next_segment(s1);
90
91 // Must have domain with trailing slash
92 if (!s2)
93 return UrlMatch{};
94
95 UrlMatch match{};
96 match.domain = make_ref(s1, s2);
97 match.valid = true;
98
99 if (only_domain || s2 >= end)
100 return match;
101
102 // Parse remaining segments only when needed
103 const char *s3 = next_segment(s2);
104 const char *s4 = s3 ? next_segment(s3) : nullptr;
105
106 StringRef seg2 = make_ref(s2, s3);
107 StringRef seg3 = s3 ? make_ref(s3, s4) : StringRef();
108 StringRef seg4 = s4 ? make_ref(s4, nullptr) : StringRef();
109
110 // Reject empty segments
111 if (seg2.empty() || (s3 && seg3.empty()) || (s4 && seg4.empty()))
112 return UrlMatch{};
113
114 // Interpret based on segment count
115 if (!s3) {
116 // 1 segment after domain: /{domain}/{entity}
117 match.id = seg2;
118 } else if (!s4) {
119 // 2 segments after domain: /{domain}/{X}/{Y}
120 // HTTP method disambiguates: GET = device/entity, POST = entity/action
121 if (is_post) {
122 match.id = seg2;
123 match.method = seg3;
124 return match;
125 }
126#ifdef USE_DEVICES
127 match.device_name = seg2;
128 match.id = seg3;
129#else
130 return UrlMatch{}; // 3-segment GET not supported without USE_DEVICES
131#endif
132 } else {
133 // 3 segments after domain: /{domain}/{device}/{entity}/{action}
134#ifdef USE_DEVICES
135 if (!is_post) {
136 return UrlMatch{}; // 4-segment GET not supported (action requires POST)
137 }
138 match.device_name = seg2;
139 match.id = seg3;
140 match.method = seg4;
141#else
142 return UrlMatch{}; // Not supported without USE_DEVICES
143#endif
144 }
145
146 return match;
147}
148
150 EntityMatchResult result{false, this->method.empty()};
151
152#ifdef USE_DEVICES
153 Device *entity_device = entity->get_device();
154 bool url_has_device = !this->device_name.empty();
155 bool entity_has_device = (entity_device != nullptr);
156
157 // Device matching: URL device segment must match entity's device
158 if (url_has_device != entity_has_device) {
159 return result; // Mismatch: one has device, other doesn't
160 }
161 if (url_has_device && this->device_name != entity_device->get_name()) {
162 return result; // Device name doesn't match
163 }
164#endif
165
166 // Match by entity name
167 if (this->id == entity->get_name()) {
168 result.matched = true;
169 }
170
171 return result;
172}
173
174#if !defined(USE_ESP32) && defined(USE_ARDUINO)
175// helper for allowing only unique entries in the queue
176void __attribute__((flatten))
178 DeferredEvent item(source, message_generator);
179
180 // Use range-based for loop instead of std::find_if to reduce template instantiation overhead and binary size
181 for (auto &event : this->deferred_queue_) {
182 if (event == item) {
183 return; // Already in queue, no need to update since items are equal
184 }
185 }
186 this->deferred_queue_.push_back(item);
187}
188
190 while (!deferred_queue_.empty()) {
191 DeferredEvent &de = deferred_queue_.front();
192 auto message = de.message_generator_(web_server_, de.source_);
193 if (this->send(message.c_str(), "state") != DISCARDED) {
194 // O(n) but memory efficiency is more important than speed here which is why std::vector was chosen
195 deferred_queue_.erase(deferred_queue_.begin());
196 this->consecutive_send_failures_ = 0; // Reset failure count on successful send
197 } else {
198 // NOTE: Similar logic exists in web_server_idf/web_server_idf.cpp in AsyncEventSourceResponse::process_buffer_()
199 // The implementations differ due to platform-specific APIs (DISCARDED vs HTTPD_SOCK_ERR_TIMEOUT, close() vs
200 // fd_.store(0)), but the failure counting and timeout logic should be kept in sync. If you change this logic,
201 // also update the ESP-IDF implementation.
204 // Too many failures, connection is likely dead
205 ESP_LOGW(TAG, "Closing stuck EventSource connection after %" PRIu16 " failed sends",
207 this->close();
208 this->deferred_queue_.clear();
209 }
210 break;
211 }
212 }
213}
214
217 // One step per loop; refusals retry next pass
219}
220
221void DeferredUpdateEventSource::deferrable_send_state(void *source, const char *event_type,
222 message_generator_t *message_generator) {
223 // Skip if no connected clients to avoid unnecessary deferred queue processing
224 if (this->count() == 0)
225 return;
226
227 // allow all json "details_all" to go through before publishing bare state events, this avoids unnamed entries showing
228 // up in the web GUI and reduces event load during initial connect
229 if (!entities_iterator_.completed() && 0 != strcmp(event_type, "state_detail_all"))
230 return;
231
232 if (source == nullptr)
233 return;
234 if (event_type == nullptr)
235 return;
236 if (message_generator == nullptr)
237 return;
238
239 if (0 != strcmp(event_type, "state_detail_all") && 0 != strcmp(event_type, "state")) {
240 ESP_LOGE(TAG, "Can't defer non-state event");
241 }
242
243 if (!deferred_queue_.empty())
245 if (!deferred_queue_.empty()) {
246 // deferred queue still not empty which means downstream event queue full, no point trying to send first
247 deq_push_back_with_dedup_(source, message_generator);
248 } else {
249 auto message = message_generator(web_server_, source);
250 if (this->send(message.c_str(), "state") == DISCARDED) {
251 deq_push_back_with_dedup_(source, message_generator);
252 } else {
253 this->consecutive_send_failures_ = 0; // Reset failure count on successful send
254 }
255 }
256}
257
258// used for logs plus the initial ping/config
259void DeferredUpdateEventSource::try_send_nodefer(const char *message, size_t message_len, const char *event,
260 uint32_t id, uint32_t reconnect) {
261 // ESPAsyncWebServer's send() only accepts null-terminated strings
262 (void) message_len;
263 this->send(message, event, id, reconnect);
264}
265
267 for (DeferredUpdateEventSource *dues : *this) {
268 dues->loop();
269 }
270 return !this->empty();
271}
272
273void DeferredUpdateEventSourceList::deferrable_send_state(void *source, const char *event_type,
274 message_generator_t *message_generator) {
275 // Skip if no event sources (no connected clients) to avoid unnecessary iteration
276 if (this->empty())
277 return;
278 for (DeferredUpdateEventSource *dues : *this) {
279 dues->deferrable_send_state(source, event_type, message_generator);
280 }
281}
282
283void DeferredUpdateEventSourceList::try_send_nodefer(const char *message, size_t message_len, const char *event,
284 uint32_t id, uint32_t reconnect) {
285 for (DeferredUpdateEventSource *dues : *this) {
286 dues->try_send_nodefer(message, message_len, event, id, reconnect);
287 }
288}
289
290void DeferredUpdateEventSourceList::add_new_client(WebServer *ws, AsyncWebServerRequest *request) {
292 this->push_back(es);
293
294 es->onConnect([this, es](AsyncEventSourceClient *client) { this->on_client_connect_(es); });
295
296 es->onDisconnect([this, es](AsyncEventSourceClient *client) { this->on_client_disconnect_(es); });
297
298 es->handleRequest(request);
300}
301
303 WebServer *ws = source->web_server_;
304 ws->defer([ws, source]() {
305 // Configure reconnect timeout and send config
306 // this should always go through since the AsyncEventSourceClient event queue is empty on connect
307 auto message = ws->get_config_json();
308 source->try_send_nodefer(message.c_str(), message.size(), "ping", millis(), 30000);
309
310#ifdef USE_WEBSERVER_SORTING
311 for (auto &group : ws->sorting_groups_) {
312 json::JsonBuilder builder;
313 JsonObject root = builder.root();
314 root[ESPHOME_F("name")] = group.second.name;
315 root[ESPHOME_F("sorting_weight")] = group.second.weight;
316 auto group_msg = builder.serialize();
317
318 // up to 31 groups should be able to be queued initially without defer
319 source->try_send_nodefer(group_msg.c_str(), group_msg.size(), "sorting_group");
320 }
321#endif
322
324 });
325}
326
328 source->web_server_->defer([this, source]() {
329 // This method was called via WebServer->defer() and is no longer executing in the
330 // context of the network callback. The object is now dead and can be safely deleted.
331 this->remove(source);
332 delete source; // NOLINT
333 });
334}
335#endif
336
338
339#ifdef USE_WEBSERVER_CSS_INCLUDE
340void WebServer::set_css_include(const char *css_include) { this->css_include_ = css_include; }
341#endif
342#ifdef USE_WEBSERVER_JS_INCLUDE
343void WebServer::set_js_include(const char *js_include) { this->js_include_ = js_include; }
344#endif
345
347 json::JsonBuilder builder;
348 JsonObject root = builder.root();
349
350 root[ESPHOME_F("title")] = App.get_friendly_name().empty() ? App.get_name().c_str() : App.get_friendly_name().c_str();
351 char comment_buffer[Application::ESPHOME_COMMENT_SIZE_MAX];
352 App.get_comment_string(comment_buffer);
353 root[ESPHOME_F("comment")] = comment_buffer;
354#if defined(USE_WEBSERVER_OTA_DISABLED) || !defined(USE_WEBSERVER_OTA)
355 root[ESPHOME_F("ota")] = false; // Note: USE_WEBSERVER_OTA_DISABLED only affects web_server, not captive_portal
356#else
357 root[ESPHOME_F("ota")] = true;
358#endif
359 root[ESPHOME_F("log")] = this->expose_log_;
360 root[ESPHOME_F("lang")] = "en";
361 root[ESPHOME_F("uptime")] = static_cast<uint32_t>(millis_64() / 1000);
362
363 return builder.serialize();
364}
365
368 this->base_->init();
369
370#ifdef USE_LOGGER
371 if (logger::global_logger != nullptr && this->expose_log_) {
373 this, [](void *self, uint8_t level, const char *tag, const char *message, size_t message_len) {
374 static_cast<WebServer *>(self)->on_log(level, tag, message, message_len);
375 });
376 }
377#endif
378
379#ifdef USE_ESP32
380 this->base_->add_handler(&this->events_);
381#endif
382 this->base_->add_handler(this);
383
384 // OTA is now handled by the web_server OTA platform
385
386 // doesn't need defer functionality - if the queue is full, the client JS knows it's alive because it's clearly
387 // getting a lot of events
388 this->set_interval(10000, [this]() {
389 if (this->events_.empty())
390 return;
391 char buf[32];
392 auto uptime = static_cast<uint32_t>(millis_64() / 1000);
393 size_t len = buf_append_printf(buf, sizeof(buf), 0, "{\"uptime\":%" PRIu32 "}", uptime);
394 this->events_.try_send_nodefer(buf, len, "ping", millis(), 30000);
395 });
396}
398 // No SSE clients connected; stop looping until a new client connects via
399 // enable_loop_soon_any_context(). This is safe because:
400 // - set_interval/set_timeout/defer run via the Scheduler, independent of loop()
401 // - deferrable_send_state early-outs when no clients are connected
402 // - try_send_nodefer (log, ping) iterates sessions which are empty
403 // - REST API handlers use defer() which runs via the Scheduler
404 if (!this->events_.loop())
405 this->disable_loop();
406}
407
408#ifdef USE_LOGGER
409void WebServer::on_log(uint8_t level, const char *tag, const char *message, size_t message_len) {
410 (void) level;
411 (void) tag;
412 this->events_.try_send_nodefer(message, message_len, "log", millis());
413}
414#endif
415
417 char addr_buf[network::USE_ADDRESS_BUFFER_SIZE];
418 ESP_LOGCONFIG(TAG,
419 "Web Server:\n"
420 " Address: %s:%u",
421 network::get_use_address_to(addr_buf), this->base_->get_port());
422}
424
425#ifdef USE_WEBSERVER_LOCAL
426void WebServer::handle_index_request(AsyncWebServerRequest *request) {
427#ifndef USE_ESP8266
428 AsyncWebServerResponse *response = request->beginResponse(200, "text/html", INDEX_GZ, sizeof(INDEX_GZ));
429#else
430 AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", INDEX_GZ, sizeof(INDEX_GZ));
431#endif
432#ifdef USE_WEBSERVER_GZIP
433 response->addHeader(ESPHOME_F("Content-Encoding"), ESPHOME_F("gzip"));
434#else
435 response->addHeader(ESPHOME_F("Content-Encoding"), ESPHOME_F("br"));
436#endif
437 request->send(response);
438}
439#elif USE_WEBSERVER_VERSION >= 2
440void WebServer::handle_index_request(AsyncWebServerRequest *request) {
441#ifndef USE_ESP8266
442 AsyncWebServerResponse *response =
443 request->beginResponse(200, "text/html", ESPHOME_WEBSERVER_INDEX_HTML, ESPHOME_WEBSERVER_INDEX_HTML_SIZE);
444#else
445 AsyncWebServerResponse *response =
446 request->beginResponse_P(200, "text/html", ESPHOME_WEBSERVER_INDEX_HTML, ESPHOME_WEBSERVER_INDEX_HTML_SIZE);
447#endif
448 // No gzip header here because the HTML file is so small
449 request->send(response);
450}
451#endif
452
453// Read a request header value portably across the Arduino and ESP-IDF web servers.
454// Returns an empty string when the header is absent (only allocates when a value is present).
455static std::string get_request_header(AsyncWebServerRequest *request, const char *name) {
456#ifdef USE_ESP32
457 // ESP32 (Arduino and ESP-IDF) uses the web_server_idf backend.
458 optional<std::string> value = request->get_header(name);
459 return value.has_value() ? std::move(*value) : std::string();
460#else
461 // ESP8266, RP2040 and LibreTiny use the Arduino ESPAsyncWebServer backend.
462 const AsyncWebHeader *header = request->getHeader(name);
463 return header != nullptr ? std::string(header->value().c_str()) : std::string();
464#endif
465}
466
467bool WebServer::is_request_origin_allowed_(AsyncWebServerRequest *request, const std::string &origin) {
468 // No Origin header: not a browser cross-origin request (e.g. curl, native API client). Allow.
469 if (origin.empty())
470 return true;
471
472 // Same-origin: the Origin authority (scheme stripped) matches the Host the request was sent to.
473 // This covers the device's own IP, mDNS name, or DNS name without knowing any at compile time.
474 const size_t scheme_sep = origin.find("://");
475 if (scheme_sep != std::string::npos) {
476 const std::string host = get_request_header(request, "Host");
477 if (!host.empty() && origin.compare(scheme_sep + 3, std::string::npos, host) == 0)
478 return true;
479 }
480
481#ifdef USE_WEBSERVER_ALLOWED_ORIGINS
482 // Otherwise the origin must be explicitly allowed via configuration.
483 for (const char *allowed_origin : this->allowed_origins_) {
484 // A single "*" entry allows any origin.
485 if (allowed_origin[0] == '*' && allowed_origin[1] == '\0')
486 return true;
487 if (origin == allowed_origin)
488 return true;
489 }
490#endif
491 return false;
492}
493
494#ifdef USE_WEBSERVER_PRIVATE_NETWORK_ACCESS
495void WebServer::handle_pna_cors_request(AsyncWebServerRequest *request) {
496 const std::string origin = get_request_header(request, "Origin");
497 if (!this->is_request_origin_allowed_(request, origin)) {
498 request->send(403);
499 return;
500 }
501
502 AsyncWebServerResponse *response = request->beginResponse(200, ESPHOME_F(""));
503 // Echo the specific origin back so the response is valid even when auth (credentials) is enabled.
504 response->addHeader(ESPHOME_F("Access-Control-Allow-Origin"), origin.empty() ? "*" : origin.c_str());
505 response->addHeader(ESPHOME_F("Access-Control-Allow-Private-Network"), ESPHOME_F("true"));
506 response->addHeader(ESPHOME_F("Private-Network-Access-Name"), App.get_name().c_str());
507 char mac_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
508 response->addHeader(ESPHOME_F("Private-Network-Access-ID"), get_mac_address_pretty_into_buffer(mac_s));
509 request->send(response);
510}
511#endif
512
513#ifdef USE_WEBSERVER_CSS_INCLUDE
514void WebServer::handle_css_request(AsyncWebServerRequest *request) {
515#ifndef USE_ESP8266
516 AsyncWebServerResponse *response =
517 request->beginResponse(200, "text/css", ESPHOME_WEBSERVER_CSS_INCLUDE, ESPHOME_WEBSERVER_CSS_INCLUDE_SIZE);
518#else
519 AsyncWebServerResponse *response =
520 request->beginResponse_P(200, "text/css", ESPHOME_WEBSERVER_CSS_INCLUDE, ESPHOME_WEBSERVER_CSS_INCLUDE_SIZE);
521#endif
522 response->addHeader(ESPHOME_F("Content-Encoding"), ESPHOME_F("gzip"));
523 request->send(response);
524}
525#endif
526
527#ifdef USE_WEBSERVER_JS_INCLUDE
528void WebServer::handle_js_request(AsyncWebServerRequest *request) {
529#ifndef USE_ESP8266
530 AsyncWebServerResponse *response =
531 request->beginResponse(200, "text/javascript", ESPHOME_WEBSERVER_JS_INCLUDE, ESPHOME_WEBSERVER_JS_INCLUDE_SIZE);
532#else
533 AsyncWebServerResponse *response =
534 request->beginResponse_P(200, "text/javascript", ESPHOME_WEBSERVER_JS_INCLUDE, ESPHOME_WEBSERVER_JS_INCLUDE_SIZE);
535#endif
536 response->addHeader(ESPHOME_F("Content-Encoding"), ESPHOME_F("gzip"));
537 request->send(response);
538}
539#endif
540
541// Helper functions to reduce code size by avoiding macro expansion
542// Build unique id as: {domain}/{device_name}/{entity_name} or {domain}/{entity_name}
543// Uses names (not object_id) to avoid UTF-8 collision issues
544static void set_json_id(JsonObject &root, EntityBase *obj, const char *prefix, JsonDetail start_config) {
545 const StringRef &name = obj->get_name();
546 size_t prefix_len = strlen(prefix);
547 size_t name_len = name.size();
548
549#ifdef USE_DEVICES
550 Device *device = obj->get_device();
551 const char *device_name = device ? device->get_name() : nullptr;
552 size_t device_len = device_name ? strlen(device_name) : 0;
553#endif
554
555 // Stack buffer for the id - ArduinoJson copies the string before it goes out of scope
556 // Buffer sizes use constants from entity_base.h validated in core/config.py
557 // Note: Device name uses ESPHOME_FRIENDLY_NAME_MAX_LEN (sub-device max 120), not ESPHOME_DEVICE_NAME_MAX_LEN
558 // (hostname)
559#ifdef USE_DEVICES
560 static constexpr size_t ID_BUF_SIZE =
561 ESPHOME_DOMAIN_MAX_LEN + 1 + ESPHOME_FRIENDLY_NAME_MAX_LEN + 1 + ESPHOME_FRIENDLY_NAME_MAX_LEN + 1;
562#else
563 static constexpr size_t ID_BUF_SIZE = ESPHOME_DOMAIN_MAX_LEN + 1 + ESPHOME_FRIENDLY_NAME_MAX_LEN + 1;
564#endif
565 char id_buf[ID_BUF_SIZE];
566 memcpy(id_buf, prefix, prefix_len); // NOLINT(bugprone-not-null-terminated-result)
567
568 char *p = id_buf + prefix_len;
569 *p++ = '/';
570#ifdef USE_DEVICES
571 if (device_name) {
572 memcpy(p, device_name, device_len);
573 p += device_len;
574 *p++ = '/';
575 }
576#endif
577 memcpy(p, name.c_str(), name_len);
578 p[name_len] = '\0';
579 root[ESPHOME_F("id")] = id_buf;
580
581 if (start_config == DETAIL_ALL) {
582 root[ESPHOME_F("domain")] = prefix;
583 // Use .c_str() to avoid instantiating set<StringRef> template (saves ~24B)
584 root[ESPHOME_F("name")] = name.c_str();
585#ifdef USE_DEVICES
586 if (device_name) {
587 root[ESPHOME_F("device")] = device_name;
588 }
589#endif
590#ifdef USE_ENTITY_ICON
591 char icon_buf[MAX_ICON_LENGTH];
592 root[ESPHOME_F("icon")] = obj->get_icon_to(icon_buf);
593#endif
594 root[ESPHOME_F("entity_category")] = obj->get_entity_category();
595 bool is_disabled = obj->is_disabled_by_default();
596 if (is_disabled)
597 root[ESPHOME_F("is_disabled_by_default")] = is_disabled;
598 }
599}
600
601// Keep as separate function even though only used once: reduces code size by ~48 bytes
602// by allowing compiler to share code between template instantiations (bool, float, etc.)
603template<typename T>
604static void set_json_value(JsonObject &root, EntityBase *obj, const char *prefix, const T &value,
605 JsonDetail start_config) {
606 set_json_id(root, obj, prefix, start_config);
607 root[ESPHOME_F("value")] = value;
608}
609
610template<typename S, typename T>
611static void set_json_icon_state_value(JsonObject &root, EntityBase *obj, const char *prefix, S state, const T &value,
612 JsonDetail start_config) {
613 set_json_value(root, obj, prefix, value, start_config);
614 root[ESPHOME_F("state")] = state;
615}
616
617// Helper to get request detail parameter
618[[maybe_unused]] static JsonDetail get_request_detail(AsyncWebServerRequest *request) {
619 return request->arg(ESPHOME_F("detail")) == "all" ? DETAIL_ALL : DETAIL_STATE;
620}
621
622#ifdef USE_SENSOR
624 if (!this->include_internal_ && obj->is_internal())
625 return;
626 this->events_.deferrable_send_state(obj, "state", sensor_state_json_generator);
627}
628void WebServer::handle_sensor_request(AsyncWebServerRequest *request, const UrlMatch &match) {
629 for (sensor::Sensor *obj : App.get_sensors()) {
630 auto entity_match = match.match_entity(obj);
631 if (!entity_match.matched)
632 continue;
633 // Note: request->method() is always HTTP_GET here (canHandle ensures this)
634 if (entity_match.action_is_empty) {
635 auto detail = get_request_detail(request);
636 auto data = this->sensor_json_(obj, obj->state, detail);
637 request->send(200, "application/json", data.c_str());
638 return;
639 }
640 }
641 request->send(404);
642}
644 return web_server->sensor_json_((sensor::Sensor *) (source), ((sensor::Sensor *) (source))->state, DETAIL_STATE);
645}
647 return web_server->sensor_json_((sensor::Sensor *) (source), ((sensor::Sensor *) (source))->state, DETAIL_ALL);
648}
649json::SerializationBuffer<> WebServer::sensor_json_(sensor::Sensor *obj, float value, JsonDetail start_config) {
650 json::JsonBuilder builder;
651 JsonObject root = builder.root();
652
653 const auto uom_ref = obj->get_unit_of_measurement_ref();
654 char buf[VALUE_ACCURACY_MAX_LEN];
655 const char *state = std::isnan(value)
656 ? "NA"
657 : (value_accuracy_with_uom_to_buf(buf, value, obj->get_accuracy_decimals(), uom_ref), buf);
658 set_json_icon_state_value(root, obj, "sensor", state, value, start_config);
659 if (start_config == DETAIL_ALL) {
660 this->add_sorting_info_(root, obj);
661 if (!uom_ref.empty())
662 root[ESPHOME_F("uom")] = uom_ref.c_str();
663 }
664
665 return builder.serialize();
666}
667#endif
668
669#ifdef USE_TEXT_SENSOR
671 if (!this->include_internal_ && obj->is_internal())
672 return;
673 this->events_.deferrable_send_state(obj, "state", text_sensor_state_json_generator);
674}
675void WebServer::handle_text_sensor_request(AsyncWebServerRequest *request, const UrlMatch &match) {
676 for (text_sensor::TextSensor *obj : App.get_text_sensors()) {
677 auto entity_match = match.match_entity(obj);
678 if (!entity_match.matched)
679 continue;
680 // Note: request->method() is always HTTP_GET here (canHandle ensures this)
681 if (entity_match.action_is_empty) {
682 auto detail = get_request_detail(request);
683 auto data = this->text_sensor_json_(obj, obj->state, detail);
684 request->send(200, "application/json", data.c_str());
685 return;
686 }
687 }
688 request->send(404);
689}
691 return web_server->text_sensor_json_((text_sensor::TextSensor *) (source),
693}
695 return web_server->text_sensor_json_((text_sensor::TextSensor *) (source),
696 ((text_sensor::TextSensor *) (source))->state, DETAIL_ALL);
697}
698json::SerializationBuffer<> WebServer::text_sensor_json_(text_sensor::TextSensor *obj, const std::string &value,
699 JsonDetail start_config) {
700 json::JsonBuilder builder;
701 JsonObject root = builder.root();
702
703 set_json_icon_state_value(root, obj, "text_sensor", value.c_str(), value.c_str(), start_config);
704 if (start_config == DETAIL_ALL) {
705 this->add_sorting_info_(root, obj);
706 }
707
708 return builder.serialize();
709}
710#endif
711
712#ifdef USE_SWITCH
714
715static void execute_switch_action(switch_::Switch *obj, SwitchAction action) {
716 switch (action) {
718 obj->toggle();
719 break;
721 obj->turn_on();
722 break;
724 obj->turn_off();
725 break;
726 default:
727 break;
728 }
729}
730
732 if (!this->include_internal_ && obj->is_internal())
733 return;
734 this->events_.deferrable_send_state(obj, "state", switch_state_json_generator);
735}
736void WebServer::handle_switch_request(AsyncWebServerRequest *request, const UrlMatch &match) {
737 for (switch_::Switch *obj : App.get_switches()) {
738 auto entity_match = match.match_entity(obj);
739 if (!entity_match.matched)
740 continue;
741
742 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
743 auto detail = get_request_detail(request);
744 auto data = this->switch_json_(obj, obj->state, detail);
745 request->send(200, "application/json", data.c_str());
746 return;
747 }
748
750
751 if (match.method_equals(ESPHOME_F("toggle"))) {
752 action = SWITCH_ACTION_TOGGLE;
753 } else if (match.method_equals(ESPHOME_F("turn_on"))) {
754 action = SWITCH_ACTION_TURN_ON;
755 } else if (match.method_equals(ESPHOME_F("turn_off"))) {
756 action = SWITCH_ACTION_TURN_OFF;
757 }
758
759 if (action != SWITCH_ACTION_NONE) {
760 this->defer([obj, action]() { execute_switch_action(obj, action); });
761 request->send(200);
762 } else {
763 request->send(404);
764 }
765 return;
766 }
767 request->send(404);
768}
770 return web_server->switch_json_((switch_::Switch *) (source), ((switch_::Switch *) (source))->state, DETAIL_STATE);
771}
773 return web_server->switch_json_((switch_::Switch *) (source), ((switch_::Switch *) (source))->state, DETAIL_ALL);
774}
775json::SerializationBuffer<> WebServer::switch_json_(switch_::Switch *obj, bool value, JsonDetail start_config) {
776 json::JsonBuilder builder;
777 JsonObject root = builder.root();
778
779 set_json_icon_state_value(root, obj, "switch", value ? "ON" : "OFF", value, start_config);
780 if (start_config == DETAIL_ALL) {
781 root[ESPHOME_F("assumed_state")] = obj->assumed_state();
782 this->add_sorting_info_(root, obj);
783 }
784
785 return builder.serialize();
786}
787#endif
788
789#ifdef USE_BUTTON
790void WebServer::handle_button_request(AsyncWebServerRequest *request, const UrlMatch &match) {
791 for (button::Button *obj : App.get_buttons()) {
792 auto entity_match = match.match_entity(obj);
793 if (!entity_match.matched)
794 continue;
795 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
796 auto detail = get_request_detail(request);
797 auto data = this->button_json_(obj, detail);
798 request->send(200, "application/json", data.c_str());
799 } else if (match.method_equals(ESPHOME_F("press"))) {
800 DEFER_ACTION(obj, obj->press());
801 request->send(200);
802 return;
803 } else {
804 request->send(404);
805 }
806 return;
807 }
808 request->send(404);
809}
811 return web_server->button_json_((button::Button *) (source), DETAIL_ALL);
812}
813json::SerializationBuffer<> WebServer::button_json_(button::Button *obj, JsonDetail start_config) {
814 json::JsonBuilder builder;
815 JsonObject root = builder.root();
816
817 set_json_id(root, obj, "button", start_config);
818 if (start_config == DETAIL_ALL) {
819 this->add_sorting_info_(root, obj);
820 }
821
822 return builder.serialize();
823}
824#endif
825
826#ifdef USE_BINARY_SENSOR
828 if (!this->include_internal_ && obj->is_internal())
829 return;
830 this->events_.deferrable_send_state(obj, "state", binary_sensor_state_json_generator);
831}
832void WebServer::handle_binary_sensor_request(AsyncWebServerRequest *request, const UrlMatch &match) {
833 for (binary_sensor::BinarySensor *obj : App.get_binary_sensors()) {
834 auto entity_match = match.match_entity(obj);
835 if (!entity_match.matched)
836 continue;
837 // Note: request->method() is always HTTP_GET here (canHandle ensures this)
838 if (entity_match.action_is_empty) {
839 auto detail = get_request_detail(request);
840 auto data = this->binary_sensor_json_(obj, obj->state, detail);
841 request->send(200, "application/json", data.c_str());
842 return;
843 }
844 }
845 request->send(404);
846}
848 return web_server->binary_sensor_json_((binary_sensor::BinarySensor *) (source),
850}
852 return web_server->binary_sensor_json_((binary_sensor::BinarySensor *) (source),
854}
855json::SerializationBuffer<> WebServer::binary_sensor_json_(binary_sensor::BinarySensor *obj, bool value,
856 JsonDetail start_config) {
857 json::JsonBuilder builder;
858 JsonObject root = builder.root();
859
860 set_json_icon_state_value(root, obj, "binary_sensor", value ? "ON" : "OFF", value, start_config);
861 if (start_config == DETAIL_ALL) {
862 this->add_sorting_info_(root, obj);
863 }
864
865 return builder.serialize();
866}
867#endif
868
869#ifdef USE_FAN
871 if (!this->include_internal_ && obj->is_internal())
872 return;
873 this->events_.deferrable_send_state(obj, "state", fan_state_json_generator);
874}
875void WebServer::handle_fan_request(AsyncWebServerRequest *request, const UrlMatch &match) {
876 for (fan::Fan *obj : App.get_fans()) {
877 auto entity_match = match.match_entity(obj);
878 if (!entity_match.matched)
879 continue;
880
881 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
882 auto detail = get_request_detail(request);
883 auto data = this->fan_json_(obj, detail);
884 request->send(200, "application/json", data.c_str());
885 } else if (match.method_equals(ESPHOME_F("toggle"))) {
886 DEFER_ACTION(obj, obj->toggle().perform());
887 request->send(200);
888 } else {
889 bool is_on = match.method_equals(ESPHOME_F("turn_on"));
890 bool is_off = match.method_equals(ESPHOME_F("turn_off"));
891 if (!is_on && !is_off) {
892 request->send(404);
893 return;
894 }
895 auto call = is_on ? obj->turn_on() : obj->turn_off();
896
897 parse_num_param_(request, ESPHOME_F("speed_level"), call, &decltype(call)::set_speed);
898
899 if (request->hasArg(ESPHOME_F("oscillation"))) {
900 auto speed = request->arg(ESPHOME_F("oscillation"));
901 auto val = parse_on_off(speed.c_str());
902 switch (val) {
903 case PARSE_ON:
904 call.set_oscillating(true);
905 break;
906 case PARSE_OFF:
907 call.set_oscillating(false);
908 break;
909 case PARSE_TOGGLE:
910 call.set_oscillating(!obj->oscillating);
911 break;
912 case PARSE_NONE:
913 request->send(404);
914 return;
915 }
916 }
917 DEFER_ACTION(call, call.perform());
918 request->send(200);
919 }
920 return;
921 }
922 request->send(404);
923}
925 return web_server->fan_json_((fan::Fan *) (source), DETAIL_STATE);
926}
928 return web_server->fan_json_((fan::Fan *) (source), DETAIL_ALL);
929}
930json::SerializationBuffer<> WebServer::fan_json_(fan::Fan *obj, JsonDetail start_config) {
931 json::JsonBuilder builder;
932 JsonObject root = builder.root();
933
934 set_json_icon_state_value(root, obj, "fan", obj->state ? "ON" : "OFF", obj->state, start_config);
935 const auto traits = obj->get_traits();
936 if (traits.supports_speed()) {
937 root[ESPHOME_F("speed_level")] = obj->speed;
938 root[ESPHOME_F("speed_count")] = traits.supported_speed_count();
939 }
940 if (obj->get_traits().supports_oscillation())
941 root[ESPHOME_F("oscillation")] = obj->oscillating;
942 if (start_config == DETAIL_ALL) {
943 this->add_sorting_info_(root, obj);
944 }
945
946 return builder.serialize();
947}
948#endif
949
950#ifdef USE_LIGHT
952 if (!this->include_internal_ && obj->is_internal())
953 return;
954 this->events_.deferrable_send_state(obj, "state", light_state_json_generator);
955}
956void WebServer::handle_light_request(AsyncWebServerRequest *request, const UrlMatch &match) {
957 for (light::LightState *obj : App.get_lights()) {
958 auto entity_match = match.match_entity(obj);
959 if (!entity_match.matched)
960 continue;
961
962 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
963 auto detail = get_request_detail(request);
964 auto data = this->light_json_(obj, detail);
965 request->send(200, "application/json", data.c_str());
966 } else if (match.method_equals(ESPHOME_F("toggle"))) {
967 DEFER_ACTION(obj, obj->toggle().perform());
968 request->send(200);
969 } else {
970 bool is_on = match.method_equals(ESPHOME_F("turn_on"));
971 bool is_off = match.method_equals(ESPHOME_F("turn_off"));
972 if (!is_on && !is_off) {
973 request->send(404);
974 return;
975 }
976 auto call = is_on ? obj->turn_on() : obj->turn_off();
977
978 if (is_on) {
979 // Parse color parameters
980 parse_light_param_(request, ESPHOME_F("brightness"), call, &decltype(call)::set_brightness, 255.0f);
981 parse_light_param_(request, ESPHOME_F("r"), call, &decltype(call)::set_red, 255.0f);
982 parse_light_param_(request, ESPHOME_F("g"), call, &decltype(call)::set_green, 255.0f);
983 parse_light_param_(request, ESPHOME_F("b"), call, &decltype(call)::set_blue, 255.0f);
984 parse_light_param_(request, ESPHOME_F("white_value"), call, &decltype(call)::set_white, 255.0f);
985 parse_light_param_(request, ESPHOME_F("color_temp"), call, &decltype(call)::set_color_temperature);
986
987 // Parse timing parameters
988 parse_light_param_uint_(request, ESPHOME_F("flash"), call, &decltype(call)::set_flash_length, 1000);
989 }
990 parse_light_param_uint_(request, ESPHOME_F("transition"), call, &decltype(call)::set_transition_length, 1000);
991
992 if (is_on) {
994 request, ESPHOME_F("effect"), call,
995 static_cast<light::LightCall &(light::LightCall::*) (const char *, size_t)>(&decltype(call)::set_effect));
996 }
997
998 DEFER_ACTION(call, call.perform());
999 request->send(200);
1000 }
1001 return;
1002 }
1003 request->send(404);
1004}
1006 return web_server->light_json_((light::LightState *) (source), DETAIL_STATE);
1007}
1009 return web_server->light_json_((light::LightState *) (source), DETAIL_ALL);
1010}
1011json::SerializationBuffer<> WebServer::light_json_(light::LightState *obj, JsonDetail start_config) {
1012 json::JsonBuilder builder;
1013 JsonObject root = builder.root();
1014
1015 set_json_value(root, obj, "light", obj->remote_values.is_on() ? "ON" : "OFF", start_config);
1016
1018 if (start_config == DETAIL_ALL) {
1019 JsonArray opt = root[ESPHOME_F("effects")].to<JsonArray>();
1020 opt.add("None");
1021 for (auto const &option : obj->get_effects()) {
1022 opt.add(option->get_name());
1023 }
1024 this->add_sorting_info_(root, obj);
1025 }
1026
1027 return builder.serialize();
1028}
1029#endif
1030
1031#ifdef USE_COVER
1033 if (!this->include_internal_ && obj->is_internal())
1034 return;
1035 this->events_.deferrable_send_state(obj, "state", cover_state_json_generator);
1036}
1037void WebServer::handle_cover_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1038 for (cover::Cover *obj : App.get_covers()) {
1039 auto entity_match = match.match_entity(obj);
1040 if (!entity_match.matched)
1041 continue;
1042
1043 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1044 auto detail = get_request_detail(request);
1045 auto data = this->cover_json_(obj, detail);
1046 request->send(200, "application/json", data.c_str());
1047 return;
1048 }
1049
1050 auto call = obj->make_call();
1051
1052 // Lookup table for cover methods
1053 static const struct {
1054 const char *name;
1055 cover::CoverCall &(cover::CoverCall::*action)();
1056 } METHODS[] = {
1061 };
1062
1063 bool found = false;
1064 for (const auto &method : METHODS) {
1065 if (match.method_equals(method.name)) {
1066 (call.*method.action)();
1067 found = true;
1068 break;
1069 }
1070 }
1071
1072 if (!found && !match.method_equals(ESPHOME_F("set"))) {
1073 request->send(404);
1074 return;
1075 }
1076
1077 auto traits = obj->get_traits();
1078 if ((request->hasArg(ESPHOME_F("position")) && !traits.get_supports_position()) ||
1079 (request->hasArg(ESPHOME_F("tilt")) && !traits.get_supports_tilt())) {
1080 request->send(409);
1081 return;
1082 }
1083
1084 parse_num_param_(request, ESPHOME_F("position"), call, &decltype(call)::set_position);
1085 parse_num_param_(request, ESPHOME_F("tilt"), call, &decltype(call)::set_tilt);
1086
1087 DEFER_ACTION(call, call.perform());
1088 request->send(200);
1089 return;
1090 }
1091 request->send(404);
1092}
1094 return web_server->cover_json_((cover::Cover *) (source), DETAIL_STATE);
1095}
1097 return web_server->cover_json_((cover::Cover *) (source), DETAIL_ALL);
1098}
1099json::SerializationBuffer<> WebServer::cover_json_(cover::Cover *obj, JsonDetail start_config) {
1100 json::JsonBuilder builder;
1101 JsonObject root = builder.root();
1102
1103 set_json_icon_state_value(root, obj, "cover", obj->is_fully_closed() ? "CLOSED" : "OPEN", obj->position,
1104 start_config);
1105 root[ESPHOME_F("current_operation")] = json_state_str(cover::cover_operation_to_str(obj->current_operation));
1106
1107 if (obj->get_traits().get_supports_position())
1108 root[ESPHOME_F("position")] = obj->position;
1109 if (obj->get_traits().get_supports_tilt())
1110 root[ESPHOME_F("tilt")] = obj->tilt;
1111 if (start_config == DETAIL_ALL) {
1112 root[ESPHOME_F("assumed_state")] = obj->get_traits().get_is_assumed_state();
1113 this->add_sorting_info_(root, obj);
1114 }
1115
1116 return builder.serialize();
1117}
1118#endif
1119
1120#ifdef USE_NUMBER
1122 if (!this->include_internal_ && obj->is_internal())
1123 return;
1124 this->events_.deferrable_send_state(obj, "state", number_state_json_generator);
1125}
1126void WebServer::handle_number_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1127 for (auto *obj : App.get_numbers()) {
1128 auto entity_match = match.match_entity(obj);
1129 if (!entity_match.matched)
1130 continue;
1131
1132 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1133 auto detail = get_request_detail(request);
1134 auto data = this->number_json_(obj, obj->state, detail);
1135 request->send(200, "application/json", data.c_str());
1136 return;
1137 }
1138 if (!match.method_equals(ESPHOME_F("set"))) {
1139 request->send(404);
1140 return;
1141 }
1142
1143 auto call = obj->make_call();
1144 parse_num_param_(request, ESPHOME_F("value"), call, &decltype(call)::set_value);
1145
1146 DEFER_ACTION(call, call.perform());
1147 request->send(200);
1148 return;
1149 }
1150 request->send(404);
1151}
1152
1154 return web_server->number_json_((number::Number *) (source), ((number::Number *) (source))->state, DETAIL_STATE);
1155}
1157 return web_server->number_json_((number::Number *) (source), ((number::Number *) (source))->state, DETAIL_ALL);
1158}
1159json::SerializationBuffer<> WebServer::number_json_(number::Number *obj, float value, JsonDetail start_config) {
1160 json::JsonBuilder builder;
1161 JsonObject root = builder.root();
1162
1163 const auto uom_ref = obj->get_unit_of_measurement_ref();
1164 const int8_t accuracy = step_to_accuracy_decimals(obj->traits.get_step());
1165
1166 // Need two buffers: one for value, one for state with UOM
1167 char val_buf[VALUE_ACCURACY_MAX_LEN];
1168 char state_buf[VALUE_ACCURACY_MAX_LEN];
1169 const char *val_str = std::isnan(value) ? "\"NaN\"" : (value_accuracy_to_buf(val_buf, value, accuracy), val_buf);
1170 const char *state_str =
1171 std::isnan(value) ? "NA" : (value_accuracy_with_uom_to_buf(state_buf, value, accuracy, uom_ref), state_buf);
1172 set_json_icon_state_value(root, obj, "number", state_str, val_str, start_config);
1173 if (start_config == DETAIL_ALL) {
1174 // ArduinoJson copies the string immediately, so we can reuse val_buf
1175 root[ESPHOME_F("min_value")] = (value_accuracy_to_buf(val_buf, obj->traits.get_min_value(), accuracy), val_buf);
1176 root[ESPHOME_F("max_value")] = (value_accuracy_to_buf(val_buf, obj->traits.get_max_value(), accuracy), val_buf);
1177 root[ESPHOME_F("step")] = (value_accuracy_to_buf(val_buf, obj->traits.get_step(), accuracy), val_buf);
1178 root[ESPHOME_F("mode")] = (int) obj->traits.get_mode();
1179 if (!uom_ref.empty())
1180 root[ESPHOME_F("uom")] = uom_ref.c_str();
1181 this->add_sorting_info_(root, obj);
1182 }
1183
1184 return builder.serialize();
1185}
1186#endif
1187
1188#ifdef USE_DATETIME_DATE
1190 if (!this->include_internal_ && obj->is_internal())
1191 return;
1192 this->events_.deferrable_send_state(obj, "state", date_state_json_generator);
1193}
1194void WebServer::handle_date_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1195 for (auto *obj : App.get_dates()) {
1196 auto entity_match = match.match_entity(obj);
1197 if (!entity_match.matched)
1198 continue;
1199 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1200 auto detail = get_request_detail(request);
1201 auto data = this->date_json_(obj, detail);
1202 request->send(200, "application/json", data.c_str());
1203 return;
1204 }
1205 if (!match.method_equals(ESPHOME_F("set"))) {
1206 request->send(404);
1207 return;
1208 }
1209
1210 auto call = obj->make_call();
1211
1212 const auto &value = request->arg(ESPHOME_F("value"));
1213 // Arduino String has isEmpty() not empty(), use length() for cross-platform compatibility
1214 if (value.length() == 0) { // NOLINT(readability-container-size-empty)
1215 request->send(409);
1216 return;
1217 }
1218 call.set_date(value.c_str(), value.length());
1219
1220 DEFER_ACTION(call, call.perform());
1221 request->send(200);
1222 return;
1223 }
1224 request->send(404);
1225}
1226
1228 return web_server->date_json_((datetime::DateEntity *) (source), DETAIL_STATE);
1229}
1231 return web_server->date_json_((datetime::DateEntity *) (source), DETAIL_ALL);
1232}
1233json::SerializationBuffer<> WebServer::date_json_(datetime::DateEntity *obj, JsonDetail start_config) {
1234 json::JsonBuilder builder;
1235 JsonObject root = builder.root();
1236
1237 // Format: YYYY-MM-DD (max 10 chars + null)
1238 char value[12];
1239 buf_append_printf(value, sizeof(value), 0, "%d-%02d-%02d", obj->year, obj->month, obj->day);
1240 set_json_icon_state_value(root, obj, "date", value, value, start_config);
1241 if (start_config == DETAIL_ALL) {
1242 this->add_sorting_info_(root, obj);
1243 }
1244
1245 return builder.serialize();
1246}
1247#endif // USE_DATETIME_DATE
1248
1249#ifdef USE_DATETIME_TIME
1251 if (!this->include_internal_ && obj->is_internal())
1252 return;
1253 this->events_.deferrable_send_state(obj, "state", time_state_json_generator);
1254}
1255void WebServer::handle_time_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1256 for (auto *obj : App.get_times()) {
1257 auto entity_match = match.match_entity(obj);
1258 if (!entity_match.matched)
1259 continue;
1260 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1261 auto detail = get_request_detail(request);
1262 auto data = this->time_json_(obj, detail);
1263 request->send(200, "application/json", data.c_str());
1264 return;
1265 }
1266 if (!match.method_equals(ESPHOME_F("set"))) {
1267 request->send(404);
1268 return;
1269 }
1270
1271 auto call = obj->make_call();
1272
1273 const auto &value = request->arg(ESPHOME_F("value"));
1274 // Arduino String has isEmpty() not empty(), use length() for cross-platform compatibility
1275 if (value.length() == 0) { // NOLINT(readability-container-size-empty)
1276 request->send(409);
1277 return;
1278 }
1279 call.set_time(value.c_str(), value.length());
1280
1281 DEFER_ACTION(call, call.perform());
1282 request->send(200);
1283 return;
1284 }
1285 request->send(404);
1286}
1288 return web_server->time_json_((datetime::TimeEntity *) (source), DETAIL_STATE);
1289}
1291 return web_server->time_json_((datetime::TimeEntity *) (source), DETAIL_ALL);
1292}
1293json::SerializationBuffer<> WebServer::time_json_(datetime::TimeEntity *obj, JsonDetail start_config) {
1294 json::JsonBuilder builder;
1295 JsonObject root = builder.root();
1296
1297 // Format: HH:MM:SS (8 chars + null)
1298 char value[12];
1299 buf_append_printf(value, sizeof(value), 0, "%02d:%02d:%02d", obj->hour, obj->minute, obj->second);
1300 set_json_icon_state_value(root, obj, "time", value, value, start_config);
1301 if (start_config == DETAIL_ALL) {
1302 this->add_sorting_info_(root, obj);
1303 }
1304
1305 return builder.serialize();
1306}
1307#endif // USE_DATETIME_TIME
1308
1309#ifdef USE_DATETIME_DATETIME
1311 if (!this->include_internal_ && obj->is_internal())
1312 return;
1313 this->events_.deferrable_send_state(obj, "state", datetime_state_json_generator);
1314}
1315void WebServer::handle_datetime_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1316 for (auto *obj : App.get_datetimes()) {
1317 auto entity_match = match.match_entity(obj);
1318 if (!entity_match.matched)
1319 continue;
1320 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1321 auto detail = get_request_detail(request);
1322 auto data = this->datetime_json_(obj, detail);
1323 request->send(200, "application/json", data.c_str());
1324 return;
1325 }
1326 if (!match.method_equals(ESPHOME_F("set"))) {
1327 request->send(404);
1328 return;
1329 }
1330
1331 auto call = obj->make_call();
1332
1333 const auto &value = request->arg(ESPHOME_F("value"));
1334 // Arduino String has isEmpty() not empty(), use length() for cross-platform compatibility
1335 if (value.length() == 0) { // NOLINT(readability-container-size-empty)
1336 request->send(409);
1337 return;
1338 }
1339 call.set_datetime(value.c_str(), value.length());
1340
1341 DEFER_ACTION(call, call.perform());
1342 request->send(200);
1343 return;
1344 }
1345 request->send(404);
1346}
1348 return web_server->datetime_json_((datetime::DateTimeEntity *) (source), DETAIL_STATE);
1349}
1351 return web_server->datetime_json_((datetime::DateTimeEntity *) (source), DETAIL_ALL);
1352}
1353json::SerializationBuffer<> WebServer::datetime_json_(datetime::DateTimeEntity *obj, JsonDetail start_config) {
1354 json::JsonBuilder builder;
1355 JsonObject root = builder.root();
1356
1357 // Format: YYYY-MM-DD HH:MM:SS (max 19 chars + null)
1358 char value[24];
1359 buf_append_printf(value, sizeof(value), 0, "%d-%02d-%02d %02d:%02d:%02d", obj->year, obj->month, obj->day, obj->hour,
1360 obj->minute, obj->second);
1361 set_json_icon_state_value(root, obj, "datetime", value, value, start_config);
1362 if (start_config == DETAIL_ALL) {
1363 this->add_sorting_info_(root, obj);
1364 }
1365
1366 return builder.serialize();
1367}
1368#endif // USE_DATETIME_DATETIME
1369
1370#ifdef USE_TEXT
1372 if (!this->include_internal_ && obj->is_internal())
1373 return;
1374 this->events_.deferrable_send_state(obj, "state", text_state_json_generator);
1375}
1376void WebServer::handle_text_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1377 for (auto *obj : App.get_texts()) {
1378 auto entity_match = match.match_entity(obj);
1379 if (!entity_match.matched)
1380 continue;
1381
1382 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1383 auto detail = get_request_detail(request);
1384 auto data = this->text_json_(obj, obj->state, detail);
1385 request->send(200, "application/json", data.c_str());
1386 return;
1387 }
1388 if (!match.method_equals(ESPHOME_F("set"))) {
1389 request->send(404);
1390 return;
1391 }
1392
1393 auto call = obj->make_call();
1395 request, ESPHOME_F("value"), call,
1396 static_cast<text::TextCall &(text::TextCall::*) (const char *, size_t)>(&decltype(call)::set_value));
1397
1398 DEFER_ACTION(call, call.perform());
1399 request->send(200);
1400 return;
1401 }
1402 request->send(404);
1403}
1404
1406 return web_server->text_json_((text::Text *) (source), ((text::Text *) (source))->state, DETAIL_STATE);
1407}
1409 return web_server->text_json_((text::Text *) (source), ((text::Text *) (source))->state, DETAIL_ALL);
1410}
1411json::SerializationBuffer<> WebServer::text_json_(text::Text *obj, const std::string &value, JsonDetail start_config) {
1412 json::JsonBuilder builder;
1413 JsonObject root = builder.root();
1414
1415 const char *state = obj->traits.get_mode() == text::TextMode::TEXT_MODE_PASSWORD ? "********" : value.c_str();
1416 set_json_icon_state_value(root, obj, "text", state, value.c_str(), start_config);
1417 root[ESPHOME_F("min_length")] = obj->traits.get_min_length();
1418 root[ESPHOME_F("max_length")] = obj->traits.get_max_length();
1419 root[ESPHOME_F("pattern")] = obj->traits.get_pattern_c_str();
1420 if (start_config == DETAIL_ALL) {
1421 root[ESPHOME_F("mode")] = (int) obj->traits.get_mode();
1422 this->add_sorting_info_(root, obj);
1423 }
1424
1425 return builder.serialize();
1426}
1427#endif
1428
1429#ifdef USE_SELECT
1431 if (!this->include_internal_ && obj->is_internal())
1432 return;
1433 this->events_.deferrable_send_state(obj, "state", select_state_json_generator);
1434}
1435void WebServer::handle_select_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1436 for (auto *obj : App.get_selects()) {
1437 auto entity_match = match.match_entity(obj);
1438 if (!entity_match.matched)
1439 continue;
1440
1441 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1442 auto detail = get_request_detail(request);
1443 auto data = this->select_json_(obj, obj->has_state() ? obj->current_option() : StringRef(), detail);
1444 request->send(200, "application/json", data.c_str());
1445 return;
1446 }
1447
1448 if (!match.method_equals(ESPHOME_F("set"))) {
1449 request->send(404);
1450 return;
1451 }
1452
1453 auto call = obj->make_call();
1455 request, ESPHOME_F("option"), call,
1456 static_cast<select::SelectCall &(select::SelectCall::*) (const char *, size_t)>(&decltype(call)::set_option));
1457
1458 DEFER_ACTION(call, call.perform());
1459 request->send(200);
1460 return;
1461 }
1462 request->send(404);
1463}
1465 auto *obj = (select::Select *) (source);
1466 return web_server->select_json_(obj, obj->has_state() ? obj->current_option() : StringRef(), DETAIL_STATE);
1467}
1469 auto *obj = (select::Select *) (source);
1470 return web_server->select_json_(obj, obj->has_state() ? obj->current_option() : StringRef(), DETAIL_ALL);
1471}
1472json::SerializationBuffer<> WebServer::select_json_(select::Select *obj, StringRef value, JsonDetail start_config) {
1473 json::JsonBuilder builder;
1474 JsonObject root = builder.root();
1475
1476 // value points to null-terminated string literals from codegen (via current_option())
1477 set_json_icon_state_value(root, obj, "select", value.c_str(), value.c_str(), start_config);
1478 if (start_config == DETAIL_ALL) {
1479 JsonArray opt = root[ESPHOME_F("option")].to<JsonArray>();
1480 for (auto &option : obj->traits.get_options()) {
1481 opt.add(option);
1482 }
1483 this->add_sorting_info_(root, obj);
1484 }
1485
1486 return builder.serialize();
1487}
1488#endif
1489
1490#ifdef USE_CLIMATE
1492 if (!this->include_internal_ && obj->is_internal())
1493 return;
1494 this->events_.deferrable_send_state(obj, "state", climate_state_json_generator);
1495}
1496void WebServer::handle_climate_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1497 for (auto *obj : App.get_climates()) {
1498 auto entity_match = match.match_entity(obj);
1499 if (!entity_match.matched)
1500 continue;
1501
1502 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1503 auto detail = get_request_detail(request);
1504 auto data = this->climate_json_(obj, detail);
1505 request->send(200, "application/json", data.c_str());
1506 return;
1507 }
1508
1509 if (!match.method_equals(ESPHOME_F("set"))) {
1510 request->send(404);
1511 return;
1512 }
1513
1514 auto call = obj->make_call();
1515
1516 // Parse string mode parameters
1518 request, ESPHOME_F("mode"), call,
1519 static_cast<climate::ClimateCall &(climate::ClimateCall::*) (const char *, size_t)>(&decltype(call)::set_mode));
1520 parse_cstr_param_(request, ESPHOME_F("fan_mode"), call,
1521 static_cast<climate::ClimateCall &(climate::ClimateCall::*) (const char *, size_t)>(
1522 &decltype(call)::set_fan_mode));
1523 parse_cstr_param_(request, ESPHOME_F("swing_mode"), call,
1524 static_cast<climate::ClimateCall &(climate::ClimateCall::*) (const char *, size_t)>(
1525 &decltype(call)::set_swing_mode));
1526 parse_cstr_param_(request, ESPHOME_F("preset"), call,
1527 static_cast<climate::ClimateCall &(climate::ClimateCall::*) (const char *, size_t)>(
1528 &decltype(call)::set_preset));
1529
1530 // Parse temperature parameters
1531 // static_cast needed to disambiguate overloaded setters (float vs optional<float>)
1532 using ClimateCall = decltype(call);
1533 parse_num_param_(request, ESPHOME_F("target_temperature_high"), call,
1534 static_cast<ClimateCall &(ClimateCall::*) (float)>(&ClimateCall::set_target_temperature_high));
1535 parse_num_param_(request, ESPHOME_F("target_temperature_low"), call,
1536 static_cast<ClimateCall &(ClimateCall::*) (float)>(&ClimateCall::set_target_temperature_low));
1537 parse_num_param_(request, ESPHOME_F("target_temperature"), call,
1538 static_cast<ClimateCall &(ClimateCall::*) (float)>(&ClimateCall::set_target_temperature));
1539
1540 DEFER_ACTION(call, call.perform());
1541 request->send(200);
1542 return;
1543 }
1544 request->send(404);
1545}
1547 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
1548 return web_server->climate_json_((climate::Climate *) (source), DETAIL_STATE);
1549}
1551 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
1552 return web_server->climate_json_((climate::Climate *) (source), DETAIL_ALL);
1553}
1554json::SerializationBuffer<> WebServer::climate_json_(climate::Climate *obj, JsonDetail start_config) {
1555 // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
1556 json::JsonBuilder builder;
1557 JsonObject root = builder.root();
1558 set_json_id(root, obj, "climate", start_config);
1559 const auto traits = obj->get_traits();
1560 int8_t target_accuracy = traits.get_target_temperature_accuracy_decimals();
1561 int8_t current_accuracy = traits.get_current_temperature_accuracy_decimals();
1562 char temp_buf[VALUE_ACCURACY_MAX_LEN];
1563
1564 if (start_config == DETAIL_ALL) {
1565 JsonArray opt = root[ESPHOME_F("modes")].to<JsonArray>();
1566 for (climate::ClimateMode m : traits.get_supported_modes())
1567 opt.add(json_state_str(climate::climate_mode_to_string(m)));
1568 if (traits.get_supports_fan_modes()) {
1569 JsonArray opt = root[ESPHOME_F("fan_modes")].to<JsonArray>();
1570 for (climate::ClimateFanMode m : traits.get_supported_fan_modes())
1571 opt.add(json_state_str(climate::climate_fan_mode_to_string(m)));
1572 }
1573
1574 if (!traits.get_supported_custom_fan_modes().empty()) {
1575 JsonArray opt = root[ESPHOME_F("custom_fan_modes")].to<JsonArray>();
1576 for (auto const &custom_fan_mode : traits.get_supported_custom_fan_modes())
1577 opt.add(custom_fan_mode);
1578 }
1579 if (traits.get_supports_swing_modes()) {
1580 JsonArray opt = root[ESPHOME_F("swing_modes")].to<JsonArray>();
1581 for (auto swing_mode : traits.get_supported_swing_modes())
1582 opt.add(json_state_str(climate::climate_swing_mode_to_string(swing_mode)));
1583 }
1584 if (traits.get_supports_presets()) {
1585 JsonArray opt = root[ESPHOME_F("presets")].to<JsonArray>();
1586 for (climate::ClimatePreset m : traits.get_supported_presets())
1587 opt.add(json_state_str(climate::climate_preset_to_string(m)));
1588 }
1589 if (!traits.get_supported_custom_presets().empty()) {
1590 JsonArray opt = root[ESPHOME_F("custom_presets")].to<JsonArray>();
1591 for (auto const &custom_preset : traits.get_supported_custom_presets())
1592 opt.add(custom_preset);
1593 }
1594 root[ESPHOME_F("max_temp")] =
1595 (value_accuracy_to_buf(temp_buf, traits.get_visual_max_temperature(), target_accuracy), temp_buf);
1596 root[ESPHOME_F("min_temp")] =
1597 (value_accuracy_to_buf(temp_buf, traits.get_visual_min_temperature(), target_accuracy), temp_buf);
1598 root[ESPHOME_F("step")] = traits.get_visual_target_temperature_step();
1599 this->add_sorting_info_(root, obj);
1600 }
1601
1602 bool has_state = false;
1603 root[ESPHOME_F("mode")] = json_state_str(climate_mode_to_string(obj->mode));
1604 if (traits.has_feature_flags(climate::CLIMATE_SUPPORTS_ACTION)) {
1605 root[ESPHOME_F("action")] = json_state_str(climate_action_to_string(obj->action));
1606 root[ESPHOME_F("state")] = root[ESPHOME_F("action")];
1607 has_state = true;
1608 }
1609 if (traits.get_supports_fan_modes() && obj->fan_mode.has_value()) {
1610 root[ESPHOME_F("fan_mode")] = json_state_str(climate_fan_mode_to_string(obj->fan_mode.value()));
1611 }
1612 if (!traits.get_supported_custom_fan_modes().empty() && obj->has_custom_fan_mode()) {
1613 root[ESPHOME_F("custom_fan_mode")] = obj->get_custom_fan_mode();
1614 }
1615 if (traits.get_supports_presets() && obj->preset.has_value()) {
1616 root[ESPHOME_F("preset")] = json_state_str(climate_preset_to_string(obj->preset.value()));
1617 }
1618 if (!traits.get_supported_custom_presets().empty() && obj->has_custom_preset()) {
1619 root[ESPHOME_F("custom_preset")] = obj->get_custom_preset();
1620 }
1621 if (traits.get_supports_swing_modes()) {
1622 root[ESPHOME_F("swing_mode")] = json_state_str(climate_swing_mode_to_string(obj->swing_mode));
1623 }
1624 if (traits.has_feature_flags(climate::CLIMATE_SUPPORTS_CURRENT_TEMPERATURE)) {
1625 root[ESPHOME_F("current_temperature")] =
1626 std::isnan(obj->current_temperature)
1627 ? "NA"
1628 : (value_accuracy_to_buf(temp_buf, obj->current_temperature, current_accuracy), temp_buf);
1629 }
1630 if (traits.has_feature_flags(climate::CLIMATE_SUPPORTS_CURRENT_HUMIDITY)) {
1631 root[ESPHOME_F("current_humidity")] = std::isnan(obj->current_humidity)
1632 ? "NA"
1633 : (value_accuracy_to_buf(temp_buf, obj->current_humidity, 0), temp_buf);
1634 }
1635 if (traits.has_feature_flags(climate::CLIMATE_SUPPORTS_TWO_POINT_TARGET_TEMPERATURE |
1637 root[ESPHOME_F("target_temperature_low")] =
1638 (value_accuracy_to_buf(temp_buf, obj->target_temperature_low, target_accuracy), temp_buf);
1639 root[ESPHOME_F("target_temperature_high")] =
1640 (value_accuracy_to_buf(temp_buf, obj->target_temperature_high, target_accuracy), temp_buf);
1641 if (!has_state) {
1642 root[ESPHOME_F("state")] =
1644 target_accuracy),
1645 temp_buf);
1646 }
1647 } else {
1648 root[ESPHOME_F("target_temperature")] =
1649 (value_accuracy_to_buf(temp_buf, obj->target_temperature, target_accuracy), temp_buf);
1650 if (!has_state)
1651 root[ESPHOME_F("state")] = root[ESPHOME_F("target_temperature")];
1652 }
1653
1654 return builder.serialize();
1655 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
1656}
1657#endif
1658
1659#ifdef USE_LOCK
1661
1662static void execute_lock_action(lock::Lock *obj, LockAction action) {
1663 switch (action) {
1664 case LOCK_ACTION_LOCK:
1665 obj->lock();
1666 break;
1667 case LOCK_ACTION_UNLOCK:
1668 obj->unlock();
1669 break;
1670 case LOCK_ACTION_OPEN:
1671 obj->open();
1672 break;
1673 default:
1674 break;
1675 }
1676}
1677
1679 if (!this->include_internal_ && obj->is_internal())
1680 return;
1681 this->events_.deferrable_send_state(obj, "state", lock_state_json_generator);
1682}
1683void WebServer::handle_lock_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1684 for (lock::Lock *obj : App.get_locks()) {
1685 auto entity_match = match.match_entity(obj);
1686 if (!entity_match.matched)
1687 continue;
1688
1689 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1690 auto detail = get_request_detail(request);
1691 auto data = this->lock_json_(obj, obj->state, detail);
1692 request->send(200, "application/json", data.c_str());
1693 return;
1694 }
1695
1697
1698 if (match.method_equals(ESPHOME_F("lock"))) {
1699 action = LOCK_ACTION_LOCK;
1700 } else if (match.method_equals(ESPHOME_F("unlock"))) {
1701 action = LOCK_ACTION_UNLOCK;
1702 } else if (match.method_equals(ESPHOME_F("open"))) {
1703 action = LOCK_ACTION_OPEN;
1704 }
1705
1706 if (action != LOCK_ACTION_NONE) {
1707 this->defer([obj, action]() { execute_lock_action(obj, action); });
1708 request->send(200);
1709 } else {
1710 request->send(404);
1711 }
1712 return;
1713 }
1714 request->send(404);
1715}
1717 return web_server->lock_json_((lock::Lock *) (source), ((lock::Lock *) (source))->state, DETAIL_STATE);
1718}
1720 return web_server->lock_json_((lock::Lock *) (source), ((lock::Lock *) (source))->state, DETAIL_ALL);
1721}
1722json::SerializationBuffer<> WebServer::lock_json_(lock::Lock *obj, lock::LockState value, JsonDetail start_config) {
1723 json::JsonBuilder builder;
1724 JsonObject root = builder.root();
1725
1726 set_json_icon_state_value(root, obj, "lock", json_state_str(lock::lock_state_to_string(value)), value, start_config);
1727 if (start_config == DETAIL_ALL) {
1728 this->add_sorting_info_(root, obj);
1729 }
1730
1731 return builder.serialize();
1732}
1733#endif
1734
1735#ifdef USE_VALVE
1737 if (!this->include_internal_ && obj->is_internal())
1738 return;
1739 this->events_.deferrable_send_state(obj, "state", valve_state_json_generator);
1740}
1741void WebServer::handle_valve_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1742 for (valve::Valve *obj : App.get_valves()) {
1743 auto entity_match = match.match_entity(obj);
1744 if (!entity_match.matched)
1745 continue;
1746
1747 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1748 auto detail = get_request_detail(request);
1749 auto data = this->valve_json_(obj, detail);
1750 request->send(200, "application/json", data.c_str());
1751 return;
1752 }
1753
1754 auto call = obj->make_call();
1755
1756 // Lookup table for valve methods
1757 static const struct {
1758 const char *name;
1759 valve::ValveCall &(valve::ValveCall::*action)();
1760 } METHODS[] = {
1765 };
1766
1767 bool found = false;
1768 for (const auto &method : METHODS) {
1769 if (match.method_equals(method.name)) {
1770 (call.*method.action)();
1771 found = true;
1772 break;
1773 }
1774 }
1775
1776 if (!found && !match.method_equals(ESPHOME_F("set"))) {
1777 request->send(404);
1778 return;
1779 }
1780
1781 auto traits = obj->get_traits();
1782 if (request->hasArg(ESPHOME_F("position")) && !traits.get_supports_position()) {
1783 request->send(409);
1784 return;
1785 }
1786
1787 parse_num_param_(request, ESPHOME_F("position"), call, &decltype(call)::set_position);
1788
1789 DEFER_ACTION(call, call.perform());
1790 request->send(200);
1791 return;
1792 }
1793 request->send(404);
1794}
1796 return web_server->valve_json_((valve::Valve *) (source), DETAIL_STATE);
1797}
1799 return web_server->valve_json_((valve::Valve *) (source), DETAIL_ALL);
1800}
1801json::SerializationBuffer<> WebServer::valve_json_(valve::Valve *obj, JsonDetail start_config) {
1802 json::JsonBuilder builder;
1803 JsonObject root = builder.root();
1804
1805 set_json_icon_state_value(root, obj, "valve", obj->is_fully_closed() ? "CLOSED" : "OPEN", obj->position,
1806 start_config);
1807 root[ESPHOME_F("current_operation")] = json_state_str(valve::valve_operation_to_str(obj->current_operation));
1808
1809 if (obj->get_traits().get_supports_position())
1810 root[ESPHOME_F("position")] = obj->position;
1811 if (start_config == DETAIL_ALL) {
1812 this->add_sorting_info_(root, obj);
1813 }
1814
1815 return builder.serialize();
1816}
1817#endif
1818
1819#ifdef USE_ALARM_CONTROL_PANEL
1821 if (!this->include_internal_ && obj->is_internal())
1822 return;
1823 this->events_.deferrable_send_state(obj, "state", alarm_control_panel_state_json_generator);
1824}
1825void WebServer::handle_alarm_control_panel_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1826 for (alarm_control_panel::AlarmControlPanel *obj : App.get_alarm_control_panels()) {
1827 auto entity_match = match.match_entity(obj);
1828 if (!entity_match.matched)
1829 continue;
1830
1831 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1832 auto detail = get_request_detail(request);
1833 auto data = this->alarm_control_panel_json_(obj, obj->get_state(), detail);
1834 request->send(200, "application/json", data.c_str());
1835 return;
1836 }
1837
1838 auto call = obj->make_call();
1840 request, ESPHOME_F("code"), call,
1842 alarm_control_panel::AlarmControlPanelCall::*) (const char *, size_t)>(&decltype(call)::set_code));
1843
1844 // Lookup table for alarm control panel methods
1845 static const struct {
1846 const char *name;
1848 } METHODS[] = {
1854 };
1855
1856 bool found = false;
1857 for (const auto &method : METHODS) {
1858 if (match.method_equals(method.name)) {
1859 (call.*method.action)();
1860 found = true;
1861 break;
1862 }
1863 }
1864
1865 if (!found) {
1866 request->send(404);
1867 return;
1868 }
1869
1870 DEFER_ACTION(call, call.perform());
1871 request->send(200);
1872 return;
1873 }
1874 request->send(404);
1875}
1877 return web_server->alarm_control_panel_json_((alarm_control_panel::AlarmControlPanel *) (source),
1878 ((alarm_control_panel::AlarmControlPanel *) (source))->get_state(),
1879 DETAIL_STATE);
1880}
1882 return web_server->alarm_control_panel_json_((alarm_control_panel::AlarmControlPanel *) (source),
1883 ((alarm_control_panel::AlarmControlPanel *) (source))->get_state(),
1884 DETAIL_ALL);
1885}
1886json::SerializationBuffer<> WebServer::alarm_control_panel_json_(alarm_control_panel::AlarmControlPanel *obj,
1888 JsonDetail start_config) {
1889 json::JsonBuilder builder;
1890 JsonObject root = builder.root();
1891
1892 set_json_icon_state_value(root, obj, "alarm_control_panel",
1893 json_state_str(alarm_control_panel_state_to_string(value)), value, start_config);
1894 if (start_config == DETAIL_ALL) {
1895 this->add_sorting_info_(root, obj);
1896 }
1897
1898 return builder.serialize();
1899}
1900#endif
1901
1902#ifdef USE_WATER_HEATER
1904 if (!this->include_internal_ && obj->is_internal())
1905 return;
1906 this->events_.deferrable_send_state(obj, "state", water_heater_state_json_generator);
1907}
1908void WebServer::handle_water_heater_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1909 for (water_heater::WaterHeater *obj : App.get_water_heaters()) {
1910 auto entity_match = match.match_entity(obj);
1911 if (!entity_match.matched)
1912 continue;
1913
1914 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1915 auto detail = get_request_detail(request);
1916 auto data = this->water_heater_json_(obj, detail);
1917 request->send(200, "application/json", data.c_str());
1918 return;
1919 }
1920 if (!match.method_equals(ESPHOME_F("set"))) {
1921 request->send(404);
1922 return;
1923 }
1924 auto call = obj->make_call();
1925 // Use base class reference for template deduction (make_call returns WaterHeaterCallInternal)
1927
1928 // Parse mode parameter
1930 request, ESPHOME_F("mode"), base_call,
1931 static_cast<water_heater::WaterHeaterCall &(water_heater::WaterHeaterCall::*) (const char *, size_t)>(
1933
1934 // Parse temperature parameters
1935 parse_num_param_(request, ESPHOME_F("target_temperature"), base_call,
1937 parse_num_param_(request, ESPHOME_F("target_temperature_low"), base_call,
1939 parse_num_param_(request, ESPHOME_F("target_temperature_high"), base_call,
1941
1942 // Parse away mode parameter
1943 parse_bool_param_(request, ESPHOME_F("away"), base_call, &water_heater::WaterHeaterCall::set_away);
1944
1945 // Parse on/off parameter
1946 parse_bool_param_(request, ESPHOME_F("is_on"), base_call, &water_heater::WaterHeaterCall::set_on);
1947
1948 DEFER_ACTION(call, call.perform());
1949 request->send(200);
1950 return;
1951 }
1952 request->send(404);
1953}
1954
1956 return web_server->water_heater_json_(static_cast<water_heater::WaterHeater *>(source), DETAIL_STATE);
1957}
1959 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
1960 return web_server->water_heater_json_(static_cast<water_heater::WaterHeater *>(source), DETAIL_ALL);
1961}
1962json::SerializationBuffer<> WebServer::water_heater_json_(water_heater::WaterHeater *obj, JsonDetail start_config) {
1963 json::JsonBuilder builder;
1964 JsonObject root = builder.root();
1965
1966 const auto mode = obj->get_mode();
1968
1969 set_json_icon_state_value(root, obj, "water_heater", mode_s, mode, start_config);
1970
1971 auto traits = obj->get_traits();
1972
1973 if (start_config == DETAIL_ALL) {
1974 JsonArray modes = root[ESPHOME_F("modes")].to<JsonArray>();
1975 for (auto m : traits.get_supported_modes())
1976 modes.add(json_state_str(water_heater::water_heater_mode_to_string(m)));
1977 root[ESPHOME_F("min_temp")] = traits.get_min_temperature();
1978 root[ESPHOME_F("max_temp")] = traits.get_max_temperature();
1979 root[ESPHOME_F("step")] = traits.get_target_temperature_step();
1980 this->add_sorting_info_(root, obj);
1981 }
1982
1983 if (traits.get_supports_current_temperature()) {
1984 float current = obj->get_current_temperature();
1985 if (!std::isnan(current))
1986 root[ESPHOME_F("current_temperature")] = current;
1987 }
1988
1989 if (traits.get_supports_two_point_target_temperature()) {
1990 float low = obj->get_target_temperature_low();
1991 float high = obj->get_target_temperature_high();
1992 if (!std::isnan(low))
1993 root[ESPHOME_F("target_temperature_low")] = low;
1994 if (!std::isnan(high))
1995 root[ESPHOME_F("target_temperature_high")] = high;
1996 } else {
1997 float target = obj->get_target_temperature();
1998 if (!std::isnan(target))
1999 root[ESPHOME_F("target_temperature")] = target;
2000 }
2001
2002 if (traits.get_supports_away_mode()) {
2003 root[ESPHOME_F("away")] = obj->is_away();
2004 }
2005
2006 if (traits.has_feature_flags(water_heater::WATER_HEATER_SUPPORTS_ON_OFF)) {
2007 root[ESPHOME_F("is_on")] = obj->is_on();
2008 }
2009
2010 return builder.serialize();
2011}
2012#endif
2013
2014#ifdef USE_INFRARED
2015void WebServer::handle_infrared_request(AsyncWebServerRequest *request, const UrlMatch &match) {
2016 for (infrared::Infrared *obj : App.get_infrareds()) {
2017 auto entity_match = match.match_entity(obj);
2018 if (!entity_match.matched)
2019 continue;
2020
2021 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
2022 auto detail = get_request_detail(request);
2023 auto data = this->infrared_json_(obj, detail);
2024 request->send(200, ESPHOME_F("application/json"), data.c_str());
2025 return;
2026 }
2027 if (!match.method_equals(ESPHOME_F("transmit"))) {
2028 request->send(404);
2029 return;
2030 }
2031
2032 // Only allow transmit if the device supports it
2033 if (!obj->has_transmitter()) {
2034 request->send(400, ESPHOME_F("text/plain"), ESPHOME_F("Device does not support transmission"));
2035 return;
2036 }
2037
2038 // Parse parameters
2039 auto call = obj->make_call();
2040
2041 // Parse carrier frequency (optional)
2042 {
2043 auto value = parse_number<uint32_t>(request->arg(ESPHOME_F("carrier_frequency")).c_str());
2044 if (value.has_value()) {
2045 call.set_carrier_frequency(*value);
2046 }
2047 }
2048
2049 // Parse repeat count (optional, defaults to 1)
2050 {
2051 auto value = parse_number<uint32_t>(request->arg(ESPHOME_F("repeat_count")).c_str());
2052 if (value.has_value()) {
2053 call.set_repeat_count(*value);
2054 }
2055 }
2056
2057 // Parse base64url-encoded raw timings (required)
2058 // Base64url is URL-safe: uses A-Za-z0-9-_ (no special characters needing escaping)
2059 const auto &data_arg = request->arg(ESPHOME_F("data"));
2060
2061 // Validate base64url is not empty (also catches missing parameter since arg() returns empty string)
2062 // Arduino String has isEmpty() not empty(), use length() for cross-platform compatibility
2063 if (data_arg.length() == 0) { // NOLINT(readability-container-size-empty)
2064 request->send(400, ESPHOME_F("text/plain"), ESPHOME_F("Missing or empty 'data' parameter"));
2065 return;
2066 }
2067
2068 // Defer to main loop for thread safety. Move encoded string into lambda to ensure
2069 // it outlives the call - set_raw_timings_base64url stores a pointer, so the string
2070 // must remain valid until perform() completes.
2071 // ESP8266 also needs this because ESPAsyncWebServer callbacks run in "sys" context.
2072 this->defer([call, encoded = std::string(data_arg.c_str(), data_arg.length())]() mutable {
2073 call.set_raw_timings_base64url(encoded);
2074 call.perform();
2075 });
2076
2077 request->send(200);
2078 return;
2079 }
2080 request->send(404);
2081}
2082
2084 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
2085 return web_server->infrared_json_(static_cast<infrared::Infrared *>(source), DETAIL_ALL);
2086}
2087
2088json::SerializationBuffer<> WebServer::infrared_json_(infrared::Infrared *obj, JsonDetail start_config) {
2089 json::JsonBuilder builder;
2090 JsonObject root = builder.root();
2091
2092 set_json_icon_state_value(root, obj, "infrared", "", 0, start_config);
2093
2094 auto traits = obj->get_traits();
2095
2096 root[ESPHOME_F("supports_transmitter")] = traits.get_supports_transmitter();
2097 root[ESPHOME_F("supports_receiver")] = traits.get_supports_receiver();
2098
2099 if (start_config == DETAIL_ALL) {
2100 this->add_sorting_info_(root, obj);
2101 }
2102
2103 return builder.serialize();
2104}
2105#endif
2106
2107#ifdef USE_RADIO_FREQUENCY
2108void WebServer::handle_radio_frequency_request(AsyncWebServerRequest *request, const UrlMatch &match) {
2109 for (radio_frequency::RadioFrequency *obj : App.get_radio_frequencies()) {
2110 auto entity_match = match.match_entity(obj);
2111 if (!entity_match.matched)
2112 continue;
2113
2114 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
2115 auto detail = get_request_detail(request);
2116 auto data = this->radio_frequency_json_(obj, detail);
2117 request->send(200, ESPHOME_F("application/json"), data.c_str());
2118 return;
2119 }
2120 if (!match.method_equals(ESPHOME_F("transmit"))) {
2121 request->send(404);
2122 return;
2123 }
2124
2125 // Only allow transmit if the device supports it
2127 request->send(400, ESPHOME_F("text/plain"), ESPHOME_F("Device does not support transmission"));
2128 return;
2129 }
2130
2131 auto call = obj->make_call();
2132
2133 // Parse carrier frequency (optional — overrides IC default)
2134 {
2135 auto value = parse_number<uint32_t>(request->arg(ESPHOME_F("frequency")).c_str());
2136 if (value.has_value()) {
2137 call.set_frequency(*value);
2138 }
2139 }
2140
2141 // Parse repeat count (optional, defaults to 1)
2142 {
2143 auto value = parse_number<uint32_t>(request->arg(ESPHOME_F("repeat_count")).c_str());
2144 if (value.has_value()) {
2145 call.set_repeat_count(*value);
2146 }
2147 }
2148
2149 // Parse base64url-encoded raw timings (required)
2150 // Base64url is URL-safe: uses A-Za-z0-9-_ (no special characters needing escaping)
2151 const auto &data_arg = request->arg(ESPHOME_F("data"));
2152
2153 // Validate base64url is not empty (also catches missing parameter since arg() returns empty string)
2154 // Arduino String has isEmpty() not empty(), use length() for cross-platform compatibility
2155 if (data_arg.length() == 0) { // NOLINT(readability-container-size-empty)
2156 request->send(400, ESPHOME_F("text/plain"), ESPHOME_F("Missing or empty 'data' parameter"));
2157 return;
2158 }
2159
2160 // Defer to main loop for thread safety. Move encoded string into lambda to ensure
2161 // it outlives the call - set_raw_timings_base64url stores a pointer, so the string
2162 // must remain valid until perform() completes.
2163 // ESP8266 also needs this because ESPAsyncWebServer callbacks run in "sys" context.
2164 this->defer([call, encoded = std::string(data_arg.c_str(), data_arg.length())]() mutable {
2165 call.set_raw_timings_base64url(encoded);
2166 call.perform();
2167 });
2168
2169 request->send(200);
2170 return;
2171 }
2172 request->send(404);
2173}
2174
2176 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
2177 return web_server->radio_frequency_json_(static_cast<radio_frequency::RadioFrequency *>(source), DETAIL_ALL);
2178}
2179
2180json::SerializationBuffer<> WebServer::radio_frequency_json_(radio_frequency::RadioFrequency *obj,
2181 JsonDetail start_config) {
2182 json::JsonBuilder builder;
2183 JsonObject root = builder.root();
2184
2185 set_json_icon_state_value(root, obj, "radio_frequency", "", 0, start_config);
2186
2187 const auto &traits = obj->get_traits();
2188 auto caps = obj->get_capability_flags();
2189
2190 root[ESPHOME_F("supports_transmitter")] = bool(caps & radio_frequency::CAPABILITY_TRANSMITTER);
2191 root[ESPHOME_F("supports_receiver")] = bool(caps & radio_frequency::CAPABILITY_RECEIVER);
2192 if (traits.get_frequency_min_hz() != 0) {
2193 root[ESPHOME_F("frequency_min")] = traits.get_frequency_min_hz();
2194 root[ESPHOME_F("frequency_max")] = traits.get_frequency_max_hz();
2195 }
2196
2197 if (start_config == DETAIL_ALL) {
2198 this->add_sorting_info_(root, obj);
2199 }
2200
2201 return builder.serialize();
2202}
2203#endif
2204
2205#ifdef USE_EVENT
2207 if (!this->include_internal_ && obj->is_internal())
2208 return;
2209 this->events_.deferrable_send_state(obj, "state", event_state_json_generator);
2210}
2211
2212void WebServer::handle_event_request(AsyncWebServerRequest *request, const UrlMatch &match) {
2213 for (event::Event *obj : App.get_events()) {
2214 auto entity_match = match.match_entity(obj);
2215 if (!entity_match.matched)
2216 continue;
2217
2218 // Note: request->method() is always HTTP_GET here (canHandle ensures this)
2219 if (entity_match.action_is_empty) {
2220 auto detail = get_request_detail(request);
2221 auto data = this->event_json_(obj, StringRef(), detail);
2222 request->send(200, "application/json", data.c_str());
2223 return;
2224 }
2225 }
2226 request->send(404);
2227}
2228
2229static StringRef get_event_type(event::Event *event) { return event ? event->get_last_event_type() : StringRef(); }
2230
2232 auto *event = static_cast<event::Event *>(source);
2233 return web_server->event_json_(event, get_event_type(event), DETAIL_STATE);
2234}
2235// NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
2237 auto *event = static_cast<event::Event *>(source);
2238 return web_server->event_json_(event, get_event_type(event), DETAIL_ALL);
2239}
2240json::SerializationBuffer<> WebServer::event_json_(event::Event *obj, StringRef event_type, JsonDetail start_config) {
2241 json::JsonBuilder builder;
2242 JsonObject root = builder.root();
2243
2244 set_json_id(root, obj, "event", start_config);
2245 if (!event_type.empty()) {
2246 root[ESPHOME_F("event_type")] = event_type;
2247 }
2248 if (start_config == DETAIL_ALL) {
2249 JsonArray event_types = root[ESPHOME_F("event_types")].to<JsonArray>();
2250 for (const char *event_type : obj->get_event_types()) {
2251 event_types.add(event_type);
2252 }
2253 char dc_buf[MAX_DEVICE_CLASS_LENGTH];
2254 root[ESPHOME_F("device_class")] = obj->get_device_class_to(dc_buf);
2255 this->add_sorting_info_(root, obj);
2256 }
2257
2258 return builder.serialize();
2259}
2260// NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
2261#endif
2262
2263#ifdef USE_UPDATE
2265 this->events_.deferrable_send_state(obj, "state", update_state_json_generator);
2266}
2267void WebServer::handle_update_request(AsyncWebServerRequest *request, const UrlMatch &match) {
2268 for (update::UpdateEntity *obj : App.get_updates()) {
2269 auto entity_match = match.match_entity(obj);
2270 if (!entity_match.matched)
2271 continue;
2272
2273 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
2274 auto detail = get_request_detail(request);
2275 auto data = this->update_json_(obj, detail);
2276 request->send(200, "application/json", data.c_str());
2277 return;
2278 }
2279
2280 if (!match.method_equals(ESPHOME_F("install"))) {
2281 request->send(404);
2282 return;
2283 }
2284
2285 DEFER_ACTION(obj, obj->perform());
2286 request->send(200);
2287 return;
2288 }
2289 request->send(404);
2290}
2292 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
2293 return web_server->update_json_((update::UpdateEntity *) (source), DETAIL_STATE);
2294}
2296 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
2297 return web_server->update_json_((update::UpdateEntity *) (source), DETAIL_ALL);
2298}
2299json::SerializationBuffer<> WebServer::update_json_(update::UpdateEntity *obj, JsonDetail start_config) {
2300 // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
2301 json::JsonBuilder builder;
2302 JsonObject root = builder.root();
2303
2304 set_json_icon_state_value(root, obj, "update", json_state_str(update::update_state_to_string(obj->state)),
2305 obj->update_info.latest_version, start_config);
2306 if (start_config == DETAIL_ALL) {
2307 root[ESPHOME_F("current_version")] = obj->update_info.current_version;
2308 root[ESPHOME_F("title")] = obj->update_info.title;
2309 // Truncate long changelogs — full text available via release_url
2310 constexpr size_t max_summary_len = 256;
2311 root[ESPHOME_F("summary")] = obj->update_info.summary.size() <= max_summary_len
2312 ? obj->update_info.summary
2313 : obj->update_info.summary.substr(0, max_summary_len);
2314 root[ESPHOME_F("release_url")] = obj->update_info.release_url;
2315 this->add_sorting_info_(root, obj);
2316 }
2317
2318 return builder.serialize();
2319 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
2320}
2321#endif
2322
2323bool WebServer::canHandle(AsyncWebServerRequest *request) const {
2324#ifdef USE_ESP32
2325 char url_buf[AsyncWebServerRequest::URL_BUF_SIZE];
2326 StringRef url = request->url_to(url_buf);
2327#else
2328 const auto &url = request->url();
2329#endif
2330 const auto method = request->method();
2331
2332 // Static URL checks - use ESPHOME_F to keep strings in flash on ESP8266
2333 if (url == ESPHOME_F("/"))
2334 return true;
2335#if !defined(USE_ESP32) && defined(USE_ARDUINO)
2336 if (url == ESPHOME_F("/events"))
2337 return true;
2338#endif
2339#ifdef USE_WEBSERVER_CSS_INCLUDE
2340 if (url == ESPHOME_F("/0.css"))
2341 return true;
2342#endif
2343#ifdef USE_WEBSERVER_JS_INCLUDE
2344 if (url == ESPHOME_F("/0.js"))
2345 return true;
2346#endif
2347
2348#ifdef USE_WEBSERVER_PRIVATE_NETWORK_ACCESS
2349 if (method == HTTP_OPTIONS && request->hasHeader(ESPHOME_F("Access-Control-Request-Private-Network")))
2350 return true;
2351#endif
2352
2353 // Parse URL for component checks
2354 UrlMatch match = match_url(url.c_str(), url.length(), true);
2355 if (!match.valid)
2356 return false;
2357
2358 // Common pattern check
2359 bool is_get = method == HTTP_GET;
2360 bool is_post = method == HTTP_POST;
2361 bool is_get_or_post = is_get || is_post;
2362
2363 if (!is_get_or_post)
2364 return false;
2365
2366 // Check GET-only domains - use ESPHOME_F to keep strings in flash on ESP8266
2367 if (is_get) {
2368#ifdef USE_SENSOR
2369 if (match.domain_equals(ESPHOME_F("sensor")))
2370 return true;
2371#endif
2372#ifdef USE_BINARY_SENSOR
2373 if (match.domain_equals(ESPHOME_F("binary_sensor")))
2374 return true;
2375#endif
2376#ifdef USE_TEXT_SENSOR
2377 if (match.domain_equals(ESPHOME_F("text_sensor")))
2378 return true;
2379#endif
2380#ifdef USE_EVENT
2381 if (match.domain_equals(ESPHOME_F("event")))
2382 return true;
2383#endif
2384 }
2385
2386 // Check GET+POST domains
2387 if (is_get_or_post) {
2388#ifdef USE_SWITCH
2389 if (match.domain_equals(ESPHOME_F("switch")))
2390 return true;
2391#endif
2392#ifdef USE_BUTTON
2393 if (match.domain_equals(ESPHOME_F("button")))
2394 return true;
2395#endif
2396#ifdef USE_FAN
2397 if (match.domain_equals(ESPHOME_F("fan")))
2398 return true;
2399#endif
2400#ifdef USE_LIGHT
2401 if (match.domain_equals(ESPHOME_F("light")))
2402 return true;
2403#endif
2404#ifdef USE_COVER
2405 if (match.domain_equals(ESPHOME_F("cover")))
2406 return true;
2407#endif
2408#ifdef USE_NUMBER
2409 if (match.domain_equals(ESPHOME_F("number")))
2410 return true;
2411#endif
2412#ifdef USE_DATETIME_DATE
2413 if (match.domain_equals(ESPHOME_F("date")))
2414 return true;
2415#endif
2416#ifdef USE_DATETIME_TIME
2417 if (match.domain_equals(ESPHOME_F("time")))
2418 return true;
2419#endif
2420#ifdef USE_DATETIME_DATETIME
2421 if (match.domain_equals(ESPHOME_F("datetime")))
2422 return true;
2423#endif
2424#ifdef USE_TEXT
2425 if (match.domain_equals(ESPHOME_F("text")))
2426 return true;
2427#endif
2428#ifdef USE_SELECT
2429 if (match.domain_equals(ESPHOME_F("select")))
2430 return true;
2431#endif
2432#ifdef USE_CLIMATE
2433 if (match.domain_equals(ESPHOME_F("climate")))
2434 return true;
2435#endif
2436#ifdef USE_LOCK
2437 if (match.domain_equals(ESPHOME_F("lock")))
2438 return true;
2439#endif
2440#ifdef USE_VALVE
2441 if (match.domain_equals(ESPHOME_F("valve")))
2442 return true;
2443#endif
2444#ifdef USE_ALARM_CONTROL_PANEL
2445 if (match.domain_equals(ESPHOME_F("alarm_control_panel")))
2446 return true;
2447#endif
2448#ifdef USE_UPDATE
2449 if (match.domain_equals(ESPHOME_F("update")))
2450 return true;
2451#endif
2452#ifdef USE_WATER_HEATER
2453 if (match.domain_equals(ESPHOME_F("water_heater")))
2454 return true;
2455#endif
2456#ifdef USE_INFRARED
2457 if (match.domain_equals(ESPHOME_F("infrared")))
2458 return true;
2459#endif
2460#ifdef USE_RADIO_FREQUENCY
2461 if (match.domain_equals(ESPHOME_F("radio_frequency")))
2462 return true;
2463#endif
2464 }
2465
2466 return false;
2467}
2468void WebServer::handleRequest(AsyncWebServerRequest *request) {
2469#ifdef USE_ESP32
2470 char url_buf[AsyncWebServerRequest::URL_BUF_SIZE];
2471 StringRef url = request->url_to(url_buf);
2472#else
2473 const auto &url = request->url();
2474#endif
2475
2476 // Handle static routes first
2477 if (url == ESPHOME_F("/")) {
2478 this->handle_index_request(request);
2479 return;
2480 }
2481
2482#ifdef USE_WEBSERVER_PRIVATE_NETWORK_ACCESS
2483 // Private Network Access preflight carries a cross-origin Origin by design; its handler does the
2484 // origin check itself, so let it run before the general enforcement below.
2485 if (request->method() == HTTP_OPTIONS && request->hasHeader(ESPHOME_F("Access-Control-Request-Private-Network"))) {
2486 this->handle_pna_cors_request(request);
2487 return;
2488 }
2489#endif
2490
2491 // Reject cross-origin browser requests unless the origin is explicitly allowed.
2492 if (!this->is_request_origin_allowed_(request, get_request_header(request, "Origin"))) {
2493 request->send(403);
2494 return;
2495 }
2496
2497#if !defined(USE_ESP32) && defined(USE_ARDUINO)
2498 if (url == ESPHOME_F("/events")) {
2499 this->events_.add_new_client(this, request);
2500 return;
2501 }
2502#endif
2503
2504#ifdef USE_WEBSERVER_CSS_INCLUDE
2505 if (url == ESPHOME_F("/0.css")) {
2506 this->handle_css_request(request);
2507 return;
2508 }
2509#endif
2510
2511#ifdef USE_WEBSERVER_JS_INCLUDE
2512 if (url == ESPHOME_F("/0.js")) {
2513 this->handle_js_request(request);
2514 return;
2515 }
2516#endif
2517
2518 // Parse URL for component routing
2519 // Pass HTTP method to disambiguate 3-segment URLs (GET=sub-device state, POST=main device action)
2520 UrlMatch match = match_url(url.c_str(), url.length(), false, request->method() == HTTP_POST);
2521
2522 // Route to appropriate handler based on domain
2523 // NOLINTNEXTLINE(readability-simplify-boolean-expr)
2524 if (false) { // Start chain for else-if macro pattern
2525 }
2526#ifdef USE_SENSOR
2527 else if (match.domain_equals(ESPHOME_F("sensor"))) {
2528 this->handle_sensor_request(request, match);
2529 }
2530#endif
2531#ifdef USE_SWITCH
2532 else if (match.domain_equals(ESPHOME_F("switch"))) {
2533 this->handle_switch_request(request, match);
2534 }
2535#endif
2536#ifdef USE_BUTTON
2537 else if (match.domain_equals(ESPHOME_F("button"))) {
2538 this->handle_button_request(request, match);
2539 }
2540#endif
2541#ifdef USE_BINARY_SENSOR
2542 else if (match.domain_equals(ESPHOME_F("binary_sensor"))) {
2543 this->handle_binary_sensor_request(request, match);
2544 }
2545#endif
2546#ifdef USE_FAN
2547 else if (match.domain_equals(ESPHOME_F("fan"))) {
2548 this->handle_fan_request(request, match);
2549 }
2550#endif
2551#ifdef USE_LIGHT
2552 else if (match.domain_equals(ESPHOME_F("light"))) {
2553 this->handle_light_request(request, match);
2554 }
2555#endif
2556#ifdef USE_TEXT_SENSOR
2557 else if (match.domain_equals(ESPHOME_F("text_sensor"))) {
2558 this->handle_text_sensor_request(request, match);
2559 }
2560#endif
2561#ifdef USE_COVER
2562 else if (match.domain_equals(ESPHOME_F("cover"))) {
2563 this->handle_cover_request(request, match);
2564 }
2565#endif
2566#ifdef USE_NUMBER
2567 else if (match.domain_equals(ESPHOME_F("number"))) {
2568 this->handle_number_request(request, match);
2569 }
2570#endif
2571#ifdef USE_DATETIME_DATE
2572 else if (match.domain_equals(ESPHOME_F("date"))) {
2573 this->handle_date_request(request, match);
2574 }
2575#endif
2576#ifdef USE_DATETIME_TIME
2577 else if (match.domain_equals(ESPHOME_F("time"))) {
2578 this->handle_time_request(request, match);
2579 }
2580#endif
2581#ifdef USE_DATETIME_DATETIME
2582 else if (match.domain_equals(ESPHOME_F("datetime"))) {
2583 this->handle_datetime_request(request, match);
2584 }
2585#endif
2586#ifdef USE_TEXT
2587 else if (match.domain_equals(ESPHOME_F("text"))) {
2588 this->handle_text_request(request, match);
2589 }
2590#endif
2591#ifdef USE_SELECT
2592 else if (match.domain_equals(ESPHOME_F("select"))) {
2593 this->handle_select_request(request, match);
2594 }
2595#endif
2596#ifdef USE_CLIMATE
2597 else if (match.domain_equals(ESPHOME_F("climate"))) {
2598 this->handle_climate_request(request, match);
2599 }
2600#endif
2601#ifdef USE_LOCK
2602 else if (match.domain_equals(ESPHOME_F("lock"))) {
2603 this->handle_lock_request(request, match);
2604 }
2605#endif
2606#ifdef USE_VALVE
2607 else if (match.domain_equals(ESPHOME_F("valve"))) {
2608 this->handle_valve_request(request, match);
2609 }
2610#endif
2611#ifdef USE_ALARM_CONTROL_PANEL
2612 else if (match.domain_equals(ESPHOME_F("alarm_control_panel"))) {
2613 this->handle_alarm_control_panel_request(request, match);
2614 }
2615#endif
2616#ifdef USE_UPDATE
2617 else if (match.domain_equals(ESPHOME_F("update"))) {
2618 this->handle_update_request(request, match);
2619 }
2620#endif
2621#ifdef USE_WATER_HEATER
2622 else if (match.domain_equals(ESPHOME_F("water_heater"))) {
2623 this->handle_water_heater_request(request, match);
2624 }
2625#endif
2626#ifdef USE_INFRARED
2627 else if (match.domain_equals(ESPHOME_F("infrared"))) {
2628 this->handle_infrared_request(request, match);
2629 }
2630#endif
2631#ifdef USE_RADIO_FREQUENCY
2632 else if (match.domain_equals(ESPHOME_F("radio_frequency"))) {
2633 this->handle_radio_frequency_request(request, match);
2634 }
2635#endif
2636 else {
2637 // No matching handler found - send 404
2638 ESP_LOGV(TAG, "Request for unknown URL: %s", url.c_str());
2639 request->send(404, ESPHOME_F("text/plain"), ESPHOME_F("Not Found"));
2640 }
2641}
2642
2643bool WebServer::isRequestHandlerTrivial() const { return false; }
2644
2645void WebServer::add_sorting_info_(JsonObject &root, EntityBase *entity) {
2646#ifdef USE_WEBSERVER_SORTING
2647 if (this->sorting_entitys_.contains(entity)) {
2648 root[ESPHOME_F("sorting_weight")] = this->sorting_entitys_[entity].weight;
2649 if (this->sorting_groups_.contains(this->sorting_entitys_[entity].group_id)) {
2650 root[ESPHOME_F("sorting_group")] = this->sorting_groups_[this->sorting_entitys_[entity].group_id].name;
2651 }
2652 }
2653#endif
2654}
2655
2656#ifdef USE_WEBSERVER_SORTING
2657void WebServer::add_entity_config(EntityBase *entity, float weight, uint64_t group) {
2658 this->sorting_entitys_[entity] = SortingComponents{weight, group};
2659}
2660
2661void WebServer::add_sorting_group(uint64_t group_id, const std::string &group_name, float weight) {
2662 this->sorting_groups_[group_id] = SortingGroup{group_name, weight};
2663}
2664#endif
2665
2666} // namespace esphome::web_server
2667#endif
BedjetMode mode
BedJet operating mode.
uint8_t m
Definition bl0906.h:1
const StringRef & get_name() const
Get the name of this Application set by pre_setup().
const StringRef & get_friendly_name() const
Get the friendly name of this Application set by pre_setup().
static constexpr size_t ESPHOME_COMMENT_SIZE_MAX
Maximum size of the comment buffer (including null terminator)
void get_comment_string(std::span< char, ESPHOME_COMMENT_SIZE_MAX > buffer)
Copy the comment string into the provided buffer.
void enable_loop_soon_any_context()
Thread and ISR-safe version of enable_loop() that can be called from any context.
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.
void set_interval(const char *name, uint32_t interval, std::function< void()> &&f)
Set an interval function with a const char* name.
Definition component.cpp:88
void begin(bool include_internal=false)
ESPHOME_ALWAYS_INLINE void try_advance(size_t max_steps)
Run up to max_steps iteration steps; stops early when iteration completes or a callback refuses (that...
static void register_controller(Controller *controller)
Register a controller to receive entity state updates.
const char * get_name()
Definition device.h:10
const char * get_device_class_to(std::span< char, MAX_DEVICE_CLASS_LENGTH > buffer) const
bool is_internal() const
Definition entity_base.h:89
const StringRef & get_name() const
Definition entity_base.h:71
ESPDEPRECATED("Use get_unit_of_measurement_ref() instead for better performance (avoids string copy). Will be " "removed in ESPHome 2026.9.0", "2026.3.0") std const char * get_icon_to(std::span< char, MAX_ICON_LENGTH > buffer) const
Get the unit of measurement as std::string (deprecated, prefer get_unit_of_measurement_ref())
bool is_disabled_by_default() const
ESPDEPRECATED("Use get_device_class_to() instead. Will be removed in ESPHome 2026.9.0", "2026.3.0") std StringRef get_unit_of_measurement_ref() const
Device * get_device() const
bool has_state() const
EntityCategory get_entity_category() const
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
constexpr size_type length() const
Definition string_ref.h:75
constexpr bool empty() const
Definition string_ref.h:76
AlarmControlPanelCall make_call()
Make a AlarmControlPanelCall.
Base class for all binary_sensor-type classes.
Base class for all buttons.
Definition button.h:25
This class is used to encode all control actions on a climate device.
Definition climate.h:34
ClimateDevice - This is the base class for all climate integrations.
Definition climate.h:187
ClimateMode mode
The active mode of the climate device.
Definition climate.h:293
optional< ClimateFanMode > fan_mode
The active fan mode of the climate device.
Definition climate.h:287
ClimateTraits get_traits()
Get the traits of this climate device with all overrides applied.
Definition climate.cpp:486
float target_temperature
The target temperature of the climate device.
Definition climate.h:274
float current_humidity
The current humidity of the climate device, as reported from the integration.
Definition climate.h:270
ClimateSwingMode swing_mode
The active swing mode of the climate device.
Definition climate.h:299
float target_temperature_low
The minimum target temperature of the climate device, for climate devices with split target temperatu...
Definition climate.h:277
bool has_custom_preset() const
Check if a custom preset is currently active.
Definition climate.h:264
float current_temperature
The current temperature of the climate device, as reported from the integration.
Definition climate.h:267
ClimateAction action
The active state of the climate device.
Definition climate.h:296
StringRef get_custom_preset() const
Get the active custom preset (read-only access). Returns StringRef.
Definition climate.h:305
bool has_custom_fan_mode() const
Check if a custom fan mode is currently active.
Definition climate.h:261
optional< ClimatePreset > preset
The active preset of the climate device.
Definition climate.h:290
float target_temperature_high
The maximum target temperature of the climate device, for climate devices with split target temperatu...
Definition climate.h:279
StringRef get_custom_fan_mode() const
Get the active custom fan mode (read-only access). Returns StringRef.
Definition climate.h:302
int8_t get_target_temperature_accuracy_decimals() const
CoverCall & set_command_toggle()
Set the command to toggle the cover.
Definition cover.cpp:58
CoverCall & set_command_open()
Set the command to open the cover.
Definition cover.cpp:46
CoverCall & set_command_close()
Set the command to close the cover.
Definition cover.cpp:50
CoverCall & set_command_stop()
Set the command to stop the cover.
Definition cover.cpp:54
Base class for all cover devices.
Definition cover.h:110
CoverOperation current_operation
The current operation of the cover (idle, opening, closing).
Definition cover.h:115
CoverCall make_call()
Construct a new cover call used to control the cover.
Definition cover.cpp:140
float tilt
The current tilt value of the cover from 0.0 to 1.0.
Definition cover.h:123
float position
The position of the cover from 0.0 (fully closed) to 1.0 (fully open).
Definition cover.h:121
bool is_fully_closed() const
Helper method to check if the cover is fully closed. Equivalent to comparing .position against 0....
Definition cover.cpp:188
virtual CoverTraits get_traits()=0
bool get_supports_position() const
bool get_is_assumed_state() const
Definition cover_traits.h:9
const FixedVector< const char * > & get_event_types() const
Return the event types supported by this event.
Definition event.h:42
FanCall turn_on()
Definition fan.cpp:156
FanCall turn_off()
Definition fan.cpp:157
virtual FanTraits get_traits()=0
FanCall toggle()
Definition fan.cpp:158
bool oscillating
The current oscillation state of the fan.
Definition fan.h:112
bool state
The current on/off state of the fan.
Definition fan.h:110
int speed
The current fan speed level.
Definition fan.h:114
bool supports_oscillation() const
Return if this fan supports oscillation.
Definition fan_traits.h:21
Infrared - Base class for infrared remote control implementations.
Definition infrared.h:114
InfraredCall make_call()
Create a call object for transmitting.
Definition infrared.cpp:78
InfraredTraits & get_traits()
Get the traits for this infrared implementation.
Definition infrared.h:133
uint32_t get_capability_flags() const
Get capability flags for this infrared instance.
Definition infrared.cpp:141
bool get_supports_transmitter() const
Definition infrared.h:98
Builder class for creating JSON documents without lambdas.
Definition json_util.h:169
SerializationBuffer serialize()
Serialize the JSON document to a SerializationBuffer (stack-first allocation) Uses 512-byte stack buf...
Definition json_util.cpp:69
Buffer for JSON serialization that uses stack allocation for small payloads.
Definition json_util.h:21
This class represents a requested change in a light state.
Definition light_call.h:22
bool is_on() const
Get the binary true/false state of these light color values.
static void dump_json(LightState &state, JsonObject root)
Dump the state of a light as JSON.
This class represents the communication layer between the front-end MQTT layer and the hardware outpu...
Definition light_state.h:93
LightColorValues remote_values
The remote color values reported to the frontend.
const FixedVector< LightEffect * > & get_effects() const
Get all effects for this light state.
Base class for all locks.
Definition lock.h:112
LockCall make_call()
Make a lock device control call, this is used to control the lock device, see the LockCall descriptio...
Definition lock.cpp:21
void lock()
Turn this lock on.
Definition lock.cpp:29
LockState state
The current reported state of the lock.
Definition lock.h:131
void unlock()
Turn this lock off.
Definition lock.cpp:30
void open()
Open (unlatch) this lock.
Definition lock.cpp:31
void add_log_callback(void *instance, void(*fn)(void *, uint8_t, const char *, const char *, size_t))
Register a log callback to receive log messages.
Definition logger.h:187
Base-class for all numbers.
Definition number.h:29
NumberCall make_call()
Definition number.h:35
NumberTraits traits
Definition number.h:41
NumberMode get_mode() const
RadioFrequency - Base class for radio frequency implementations.
uint32_t get_capability_flags() const
Get capability flags for this radio frequency instance.
RadioFrequencyTraits & get_traits()
Get the traits for this radio frequency implementation.
Base-class for all selects.
Definition select.h:29
SelectCall make_call()
Instantiate a SelectCall object to modify this select component's state.
Definition select.h:46
SelectTraits traits
Definition select.h:31
const FixedVector< const char * > & get_options() const
Base-class for all sensors.
Definition sensor.h:47
float state
This member variable stores the last state that has passed through all filters.
Definition sensor.h:138
int8_t get_accuracy_decimals()
Get the accuracy in decimals, using the manual override if set.
Definition sensor.cpp:48
Base class for all switches.
Definition switch.h:38
void toggle()
Toggle this switch.
Definition switch.cpp:28
void turn_on()
Turn this switch on.
Definition switch.cpp:20
void turn_off()
Turn this switch off.
Definition switch.cpp:24
bool state
The current reported state of the binary sensor.
Definition switch.h:55
virtual bool assumed_state()
Return whether this switch uses an assumed state - i.e.
Definition switch.cpp:70
Base-class for all text inputs.
Definition text.h:21
TextCall make_call()
Instantiate a TextCall object to modify this text component's state.
Definition text.h:31
TextTraits traits
Definition text.h:24
TextMode get_mode() const
Definition text_traits.h:30
const char * get_pattern_c_str() const
Definition text_traits.h:25
const UpdateState & state
const UpdateInfo & update_info
ValveCall & set_command_close()
Set the command to close the valve.
Definition valve.cpp:53
ValveCall & set_command_toggle()
Set the command to toggle the valve.
Definition valve.cpp:61
ValveCall & set_command_stop()
Set the command to stop the valve.
Definition valve.cpp:57
ValveCall & set_command_open()
Set the command to open the valve.
Definition valve.cpp:49
Base class for all valve devices.
Definition valve.h:103
bool is_fully_closed() const
Helper method to check if the valve is fully closed. Equivalent to comparing .position against 0....
Definition valve.cpp:166
float position
The position of the valve from 0.0 (fully closed) to 1.0 (fully open).
Definition valve.h:114
ValveCall make_call()
Construct a new valve call used to control the valve.
Definition valve.cpp:125
ValveOperation current_operation
The current operation of the valve (idle, opening, closing).
Definition valve.h:108
virtual ValveTraits get_traits()=0
bool get_supports_position() const
WaterHeaterCall & set_away(bool away)
WaterHeaterCall & set_target_temperature_high(float temperature)
WaterHeaterCall & set_mode(WaterHeaterMode mode)
WaterHeaterCall & set_target_temperature_low(float temperature)
WaterHeaterCall & set_on(bool on)
WaterHeaterCall & set_target_temperature(float temperature)
bool is_on() const
Check if the water heater is on.
bool is_away() const
Check if away mode is currently active.
virtual WaterHeaterCallInternal make_call()=0
WaterHeaterMode get_mode() const
virtual WaterHeaterTraits get_traits()
static constexpr uint16_t MAX_CONSECUTIVE_SEND_FAILURES
Definition web_server.h:149
void deq_push_back_with_dedup_(void *source, message_generator_t *message_generator)
void try_send_nodefer(const char *message, size_t message_len, const char *event=nullptr, uint32_t id=0, uint32_t reconnect=0)
void deferrable_send_state(void *source, const char *event_type, message_generator_t *message_generator)
std::vector< DeferredEvent > deferred_queue_
Definition web_server.h:146
void on_client_connect_(DeferredUpdateEventSource *source)
void try_send_nodefer(const char *message, size_t message_len, const char *event=nullptr, uint32_t id=0, uint32_t reconnect=0)
void add_new_client(WebServer *ws, AsyncWebServerRequest *request)
void deferrable_send_state(void *source, const char *event_type, message_generator_t *message_generator)
void on_client_disconnect_(DeferredUpdateEventSource *source)
bool loop()
Returns true if there are event sources remaining (including pending cleanup).
This class allows users to create a web server with their ESP nodes.
Definition web_server.h:193
void setup() override
Setup the internal web server and register handlers.
void on_update(update::UpdateEntity *obj) override
static json::SerializationBuffer radio_frequency_all_json_generator(WebServer *web_server, void *source)
void on_water_heater_update(water_heater::WaterHeater *obj) override
json::SerializationBuffer get_config_json()
Return the webserver configuration as JSON.
std::map< EntityBase *, SortingComponents > sorting_entitys_
Definition web_server.h:521
static json::SerializationBuffer text_state_json_generator(WebServer *web_server, void *source)
void on_text_update(text::Text *obj) override
void on_light_update(light::LightState *obj) override
static json::SerializationBuffer datetime_state_json_generator(WebServer *web_server, void *source)
void on_cover_update(cover::Cover *obj) override
static json::SerializationBuffer lock_all_json_generator(WebServer *web_server, void *source)
static json::SerializationBuffer alarm_control_panel_all_json_generator(WebServer *web_server, void *source)
static json::SerializationBuffer text_all_json_generator(WebServer *web_server, void *source)
static json::SerializationBuffer switch_all_json_generator(WebServer *web_server, void *source)
void handle_select_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a select request under '/select/<id>'.
void on_log(uint8_t level, const char *tag, const char *message, size_t message_len)
static json::SerializationBuffer event_all_json_generator(WebServer *web_server, void *source)
static json::SerializationBuffer update_all_json_generator(WebServer *web_server, void *source)
static json::SerializationBuffer text_sensor_all_json_generator(WebServer *web_server, void *source)
void handle_water_heater_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a water_heater request under '/water_heater/<id>/<mode/set>'.
bool isRequestHandlerTrivial() const override
This web handle is not trivial.
static json::SerializationBuffer cover_all_json_generator(WebServer *web_server, void *source)
WebServer(web_server_base::WebServerBase *base)
void handle_switch_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a switch request under '/switch/<id>/</turn_on/turn_off/toggle>'.
void handle_event_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a event request under '/event<id>'.
void parse_light_param_uint_(AsyncWebServerRequest *request, ParamNameType param_name, T &call, Ret(T::*setter)(uint32_t), uint32_t scale=1)
Definition web_server.h:543
static json::SerializationBuffer datetime_all_json_generator(WebServer *web_server, void *source)
static json::SerializationBuffer light_state_json_generator(WebServer *web_server, void *source)
static json::SerializationBuffer climate_state_json_generator(WebServer *web_server, void *source)
void handle_button_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a button request under '/button/<id>/press'.
void on_date_update(datetime::DateEntity *obj) override
static json::SerializationBuffer date_all_json_generator(WebServer *web_server, void *source)
static json::SerializationBuffer sensor_state_json_generator(WebServer *web_server, void *source)
void on_number_update(number::Number *obj) override
void add_entity_config(EntityBase *entity, float weight, uint64_t group)
void handle_radio_frequency_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a radio frequency request under '/radio_frequency/<id>/transmit'.
void parse_light_param_(AsyncWebServerRequest *request, ParamNameType param_name, T &call, Ret(T::*setter)(float), float scale=1.0f)
Definition web_server.h:533
void handle_css_request(AsyncWebServerRequest *request)
Handle included css request under '/0.css'.
static json::SerializationBuffer select_all_json_generator(WebServer *web_server, void *source)
static json::SerializationBuffer infrared_all_json_generator(WebServer *web_server, void *source)
void on_valve_update(valve::Valve *obj) override
void on_climate_update(climate::Climate *obj) override
void add_sorting_info_(JsonObject &root, EntityBase *entity)
void handle_light_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a light request under '/light/<id>/</turn_on/turn_off/toggle>'.
static json::SerializationBuffer sensor_all_json_generator(WebServer *web_server, void *source)
void on_binary_sensor_update(binary_sensor::BinarySensor *obj) override
void handle_text_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a text input request under '/text/<id>'.
static json::SerializationBuffer number_all_json_generator(WebServer *web_server, void *source)
void handle_cover_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a cover request under '/cover/<id>/<open/close/stop/set>'.
static json::SerializationBuffer select_state_json_generator(WebServer *web_server, void *source)
void on_switch_update(switch_::Switch *obj) override
static json::SerializationBuffer water_heater_state_json_generator(WebServer *web_server, void *source)
web_server_base::WebServerBase * base_
Definition web_server.h:594
void handle_lock_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a lock request under '/lock/<id>/</lock/unlock/open>'.
void on_alarm_control_panel_update(alarm_control_panel::AlarmControlPanel *obj) override
static json::SerializationBuffer time_state_json_generator(WebServer *web_server, void *source)
void handle_text_sensor_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a text sensor request under '/text_sensor/<id>'.
void parse_bool_param_(AsyncWebServerRequest *request, ParamNameType param_name, T &call, Ret(T::*setter)(bool))
Definition web_server.h:576
bool is_request_origin_allowed_(AsyncWebServerRequest *request, const std::string &origin)
Check whether the given request Origin is permitted.
void handle_date_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a date request under '/date/<id>'.
void handle_infrared_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle an infrared request under '/infrared/<id>/transmit'.
void handle_sensor_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a sensor request under '/sensor/<id>'.
void handle_number_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a number request under '/number/<id>'.
void handle_index_request(AsyncWebServerRequest *request)
Handle an index request under '/'.
void handle_js_request(AsyncWebServerRequest *request)
Handle included js request under '/0.js'.
static json::SerializationBuffer valve_state_json_generator(WebServer *web_server, void *source)
static json::SerializationBuffer fan_all_json_generator(WebServer *web_server, void *source)
void set_js_include(const char *js_include)
Set local path to the script that's embedded in the index page.
static json::SerializationBuffer lock_state_json_generator(WebServer *web_server, void *source)
static json::SerializationBuffer update_state_json_generator(WebServer *web_server, void *source)
void handleRequest(AsyncWebServerRequest *request) override
Override the web handler's handleRequest method.
static json::SerializationBuffer button_all_json_generator(WebServer *web_server, void *source)
void on_datetime_update(datetime::DateTimeEntity *obj) override
void handle_fan_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a fan request under '/fan/<id>/</turn_on/turn_off/toggle>'.
static json::SerializationBuffer alarm_control_panel_state_json_generator(WebServer *web_server, void *source)
static json::SerializationBuffer time_all_json_generator(WebServer *web_server, void *source)
void parse_cstr_param_(AsyncWebServerRequest *request, ParamNameType param_name, T &call, Ret(T::*setter)(const char *, size_t))
Definition web_server.h:563
static json::SerializationBuffer water_heater_all_json_generator(WebServer *web_server, void *source)
void handle_valve_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a valve request under '/valve/<id>/<open/close/stop/set>'.
static json::SerializationBuffer date_state_json_generator(WebServer *web_server, void *source)
void handle_binary_sensor_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a binary sensor request under '/binary_sensor/<id>'.
void handle_time_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a time request under '/time/<id>'.
void on_sensor_update(sensor::Sensor *obj) override
std::map< uint64_t, SortingGroup > sorting_groups_
Definition web_server.h:522
void set_css_include(const char *css_include)
Set local path to the script that's embedded in the index page.
FixedVector< const char * > allowed_origins_
Definition web_server.h:615
bool canHandle(AsyncWebServerRequest *request) const override
Override the web handler's canHandle method.
static json::SerializationBuffer climate_all_json_generator(WebServer *web_server, void *source)
static json::SerializationBuffer fan_state_json_generator(WebServer *web_server, void *source)
void on_event(event::Event *obj) override
static json::SerializationBuffer cover_state_json_generator(WebServer *web_server, void *source)
void handle_pna_cors_request(AsyncWebServerRequest *request)
static json::SerializationBuffer binary_sensor_state_json_generator(WebServer *web_server, void *source)
void on_fan_update(fan::Fan *obj) override
void handle_datetime_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a datetime request under '/datetime/<id>'.
static json::SerializationBuffer event_state_json_generator(WebServer *web_server, void *source)
static json::SerializationBuffer binary_sensor_all_json_generator(WebServer *web_server, void *source)
void handle_alarm_control_panel_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a alarm_control_panel request under '/alarm_control_panel/<id>'.
void on_lock_update(lock::Lock *obj) override
static json::SerializationBuffer switch_state_json_generator(WebServer *web_server, void *source)
float get_setup_priority() const override
MQTT setup priority.
void on_select_update(select::Select *obj) override
void on_time_update(datetime::TimeEntity *obj) override
void parse_num_param_(AsyncWebServerRequest *request, ParamNameType param_name, T &call, Ret(T::*setter)(NumT))
Definition web_server.h:554
static json::SerializationBuffer text_sensor_state_json_generator(WebServer *web_server, void *source)
static json::SerializationBuffer number_state_json_generator(WebServer *web_server, void *source)
static json::SerializationBuffer valve_all_json_generator(WebServer *web_server, void *source)
void handle_update_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a update request under '/update/<id>'.
static json::SerializationBuffer light_all_json_generator(WebServer *web_server, void *source)
void add_sorting_group(uint64_t group_id, const std::string &group_name, float weight)
void handle_climate_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a climate request under '/climate/<id>'.
void on_text_sensor_update(text_sensor::TextSensor *obj) override
void add_handler(AsyncWebHandler *handler)
ClimateSwingMode swing_mode
Definition climate.h:11
struct @66::@67 __attribute__
Wake the main loop task from an ISR. ISR-safe.
Definition main_task.h:32
uint8_t custom_preset
Definition climate.h:9
uint8_t custom_fan_mode
Definition climate.h:4
const LogString * message
Definition component.cpp:35
int speed
Definition fan.h:3
bool state
Definition fan.h:2
mopeka_std_values val[3]
const LogString * climate_action_to_string(ClimateAction action)
Convert the given ClimateAction to a human-readable string.
@ CLIMATE_SUPPORTS_CURRENT_HUMIDITY
@ CLIMATE_SUPPORTS_TWO_POINT_TARGET_TEMPERATURE
@ CLIMATE_SUPPORTS_CURRENT_TEMPERATURE
@ CLIMATE_REQUIRES_TWO_POINT_TARGET_TEMPERATURE
const LogString * climate_swing_mode_to_string(ClimateSwingMode swing_mode)
Convert the given ClimateSwingMode to a human-readable string.
const LogString * climate_preset_to_string(ClimatePreset preset)
Convert the given PresetMode to a human-readable string.
ClimatePreset
Enum for all preset modes NOTE: If adding values, update ClimatePresetMask in climate_traits....
const LogString * climate_fan_mode_to_string(ClimateFanMode fan_mode)
Convert the given ClimateFanMode to a human-readable string.
ClimateMode
Enum for all modes a climate device can be in.
const LogString * climate_mode_to_string(ClimateMode mode)
Convert the given ClimateMode to a human-readable string.
ClimateFanMode
NOTE: If adding values, update ClimateFanModeMask in climate_traits.h to use the new last value.
const LogString * cover_operation_to_str(CoverOperation op)
Definition cover.cpp:25
const LogString * lock_state_to_string(LockState state)
Definition lock.cpp:16
LockState
Enum for all states a lock can be in.
Definition lock.h:23
Logger * global_logger
Definition logger.cpp:279
const char * get_use_address_to(std::span< char, USE_ADDRESS_BUFFER_SIZE > buf)
Get the active network address for logging.
Definition util.cpp:42
constexpr float WIFI
Definition component.h:50
const char *const TAG
Definition spi.cpp:7
const LogString * update_state_to_string(UpdateState state)
const LogString * valve_operation_to_str(ValveOperation op)
Definition valve.cpp:28
@ WATER_HEATER_SUPPORTS_ON_OFF
The water heater can be turned on/off.
const LogString * water_heater_mode_to_string(WaterHeaterMode mode)
Convert the given WaterHeaterMode to a human-readable string for logging.
const char * tag
Definition log.h:74
size_t value_accuracy_to_buf(std::span< char, VALUE_ACCURACY_MAX_LEN > buf, float value, int8_t accuracy_decimals)
Format value with accuracy to buffer, returns chars written (excluding null)
Definition helpers.cpp:539
ParseOnOffState parse_on_off(const char *str, const char *on, const char *off)
Parse a string that contains either on, off or toggle.
Definition helpers.cpp:466
const void size_t len
Definition hal.h:64
if(written< 0)
Definition helpers.h:1071
optional< T > parse_number(const char *str)
Parse an unsigned decimal number from a null-terminated string.
Definition helpers.h:1167
int8_t step_to_accuracy_decimals(float step)
Derive accuracy in decimals from an increment step.
Definition helpers.cpp:569
uint64_t millis_64()
Definition hal.cpp:29
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:816
size_t value_accuracy_with_uom_to_buf(std::span< char, VALUE_ACCURACY_MAX_LEN > buf, float value, int8_t accuracy_decimals, StringRef unit_of_measurement)
Format value with accuracy and UOM to buffer, returns chars written (excluding null)
Definition helpers.cpp:558
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:28
Application App
Global storage of Application pointer - only one Application can exist.
@ PARSE_ON
Definition helpers.h:1593
@ PARSE_TOGGLE
Definition helpers.h:1595
@ PARSE_OFF
Definition helpers.h:1594
@ PARSE_NONE
Definition helpers.h:1592
STL namespace.
const __FlashStringHelper * ProgmemStr
Definition progmem.h:27
static void uint32_t
Result of matching a URL against an entity.
Definition web_server.h:54
Internal helper struct that is used to parse incoming URLs.
Definition web_server.h:60
StringRef device_name
Device name within URL, empty for main device.
Definition web_server.h:65
bool valid
Whether this match is valid.
Definition web_server.h:67
EntityMatchResult match_entity(EntityBase *entity) const
Match entity by name Returns EntityMatchResult with match status and whether action segment is empty.
StringRef method
Method within URL, for example "turn_on".
Definition web_server.h:63
bool domain_equals(const char *str) const
Definition web_server.h:70
bool method_equals(const char *str) const
Definition web_server.h:71
uint8_t end[39]
Definition sun_gtil2.cpp:17
const size_t ESPHOME_WEBSERVER_INDEX_HTML_SIZE
const size_t ESPHOME_WEBSERVER_CSS_INCLUDE_SIZE
const size_t ESPHOME_WEBSERVER_JS_INCLUDE_SIZE