ESPHome 2026.8.0
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
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 // just dump them all up-front and take advantage of the deferred queue
326 // on second thought that takes too long, but leaving the commented code here for debug purposes
327 // while(!source->entities_iterator_.completed()) {
328 // source->entities_iterator_.advance();
329 //}
330 });
331}
332
334 source->web_server_->defer([this, source]() {
335 // This method was called via WebServer->defer() and is no longer executing in the
336 // context of the network callback. The object is now dead and can be safely deleted.
337 this->remove(source);
338 delete source; // NOLINT
339 });
340}
341#endif
342
344
345#ifdef USE_WEBSERVER_CSS_INCLUDE
346void WebServer::set_css_include(const char *css_include) { this->css_include_ = css_include; }
347#endif
348#ifdef USE_WEBSERVER_JS_INCLUDE
349void WebServer::set_js_include(const char *js_include) { this->js_include_ = js_include; }
350#endif
351
353 json::JsonBuilder builder;
354 JsonObject root = builder.root();
355
356 root[ESPHOME_F("title")] = App.get_friendly_name().empty() ? App.get_name().c_str() : App.get_friendly_name().c_str();
357 char comment_buffer[Application::ESPHOME_COMMENT_SIZE_MAX];
358 App.get_comment_string(comment_buffer);
359 root[ESPHOME_F("comment")] = comment_buffer;
360#if defined(USE_WEBSERVER_OTA_DISABLED) || !defined(USE_WEBSERVER_OTA)
361 root[ESPHOME_F("ota")] = false; // Note: USE_WEBSERVER_OTA_DISABLED only affects web_server, not captive_portal
362#else
363 root[ESPHOME_F("ota")] = true;
364#endif
365 root[ESPHOME_F("log")] = this->expose_log_;
366 root[ESPHOME_F("lang")] = "en";
367 root[ESPHOME_F("uptime")] = static_cast<uint32_t>(millis_64() / 1000);
368
369 return builder.serialize();
370}
371
374 this->base_->init();
375
376#ifdef USE_LOGGER
377 if (logger::global_logger != nullptr && this->expose_log_) {
379 this, [](void *self, uint8_t level, const char *tag, const char *message, size_t message_len) {
380 static_cast<WebServer *>(self)->on_log(level, tag, message, message_len);
381 });
382 }
383#endif
384
385#ifdef USE_ESP32
386 this->base_->add_handler(&this->events_);
387#endif
388 this->base_->add_handler(this);
389
390 // OTA is now handled by the web_server OTA platform
391
392 // doesn't need defer functionality - if the queue is full, the client JS knows it's alive because it's clearly
393 // getting a lot of events
394 this->set_interval(10000, [this]() {
395 if (this->events_.empty())
396 return;
397 char buf[32];
398 auto uptime = static_cast<uint32_t>(millis_64() / 1000);
399 size_t len = buf_append_printf(buf, sizeof(buf), 0, "{\"uptime\":%" PRIu32 "}", uptime);
400 this->events_.try_send_nodefer(buf, len, "ping", millis(), 30000);
401 });
402}
404 // No SSE clients connected; stop looping until a new client connects via
405 // enable_loop_soon_any_context(). This is safe because:
406 // - set_interval/set_timeout/defer run via the Scheduler, independent of loop()
407 // - deferrable_send_state early-outs when no clients are connected
408 // - try_send_nodefer (log, ping) iterates sessions which are empty
409 // - REST API handlers use defer() which runs via the Scheduler
410 if (!this->events_.loop())
411 this->disable_loop();
412}
413
414#ifdef USE_LOGGER
415void WebServer::on_log(uint8_t level, const char *tag, const char *message, size_t message_len) {
416 (void) level;
417 (void) tag;
418 this->events_.try_send_nodefer(message, message_len, "log", millis());
419}
420#endif
421
423 char addr_buf[network::USE_ADDRESS_BUFFER_SIZE];
424 ESP_LOGCONFIG(TAG,
425 "Web Server:\n"
426 " Address: %s:%u",
427 network::get_use_address_to(addr_buf), this->base_->get_port());
428}
430
431#ifdef USE_WEBSERVER_LOCAL
432void WebServer::handle_index_request(AsyncWebServerRequest *request) {
433#ifndef USE_ESP8266
434 AsyncWebServerResponse *response = request->beginResponse(200, "text/html", INDEX_GZ, sizeof(INDEX_GZ));
435#else
436 AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", INDEX_GZ, sizeof(INDEX_GZ));
437#endif
438#ifdef USE_WEBSERVER_GZIP
439 response->addHeader(ESPHOME_F("Content-Encoding"), ESPHOME_F("gzip"));
440#else
441 response->addHeader(ESPHOME_F("Content-Encoding"), ESPHOME_F("br"));
442#endif
443 request->send(response);
444}
445#elif USE_WEBSERVER_VERSION >= 2
446void WebServer::handle_index_request(AsyncWebServerRequest *request) {
447#ifndef USE_ESP8266
448 AsyncWebServerResponse *response =
449 request->beginResponse(200, "text/html", ESPHOME_WEBSERVER_INDEX_HTML, ESPHOME_WEBSERVER_INDEX_HTML_SIZE);
450#else
451 AsyncWebServerResponse *response =
452 request->beginResponse_P(200, "text/html", ESPHOME_WEBSERVER_INDEX_HTML, ESPHOME_WEBSERVER_INDEX_HTML_SIZE);
453#endif
454 // No gzip header here because the HTML file is so small
455 request->send(response);
456}
457#endif
458
459// Read a request header value portably across the Arduino and ESP-IDF web servers.
460// Returns an empty string when the header is absent (only allocates when a value is present).
461static std::string get_request_header(AsyncWebServerRequest *request, const char *name) {
462#ifdef USE_ESP32
463 // ESP32 (Arduino and ESP-IDF) uses the web_server_idf backend.
464 optional<std::string> value = request->get_header(name);
465 return value.has_value() ? std::move(*value) : std::string();
466#else
467 // ESP8266, RP2040 and LibreTiny use the Arduino ESPAsyncWebServer backend.
468 const AsyncWebHeader *header = request->getHeader(name);
469 return header != nullptr ? std::string(header->value().c_str()) : std::string();
470#endif
471}
472
473bool WebServer::is_request_origin_allowed_(AsyncWebServerRequest *request, const std::string &origin) {
474 // No Origin header: not a browser cross-origin request (e.g. curl, native API client). Allow.
475 if (origin.empty())
476 return true;
477
478 // Same-origin: the Origin authority (scheme stripped) matches the Host the request was sent to.
479 // This covers the device's own IP, mDNS name, or DNS name without knowing any at compile time.
480 const size_t scheme_sep = origin.find("://");
481 if (scheme_sep != std::string::npos) {
482 const std::string host = get_request_header(request, "Host");
483 if (!host.empty() && origin.compare(scheme_sep + 3, std::string::npos, host) == 0)
484 return true;
485 }
486
487#ifdef USE_WEBSERVER_ALLOWED_ORIGINS
488 // Otherwise the origin must be explicitly allowed via configuration.
489 for (const char *allowed_origin : this->allowed_origins_) {
490 // A single "*" entry allows any origin.
491 if (allowed_origin[0] == '*' && allowed_origin[1] == '\0')
492 return true;
493 if (origin == allowed_origin)
494 return true;
495 }
496#endif
497 return false;
498}
499
500#ifdef USE_WEBSERVER_PRIVATE_NETWORK_ACCESS
501void WebServer::handle_pna_cors_request(AsyncWebServerRequest *request) {
502 const std::string origin = get_request_header(request, "Origin");
503 if (!this->is_request_origin_allowed_(request, origin)) {
504 request->send(403);
505 return;
506 }
507
508 AsyncWebServerResponse *response = request->beginResponse(200, ESPHOME_F(""));
509 // Echo the specific origin back so the response is valid even when auth (credentials) is enabled.
510 response->addHeader(ESPHOME_F("Access-Control-Allow-Origin"), origin.empty() ? "*" : origin.c_str());
511 response->addHeader(ESPHOME_F("Access-Control-Allow-Private-Network"), ESPHOME_F("true"));
512 response->addHeader(ESPHOME_F("Private-Network-Access-Name"), App.get_name().c_str());
513 char mac_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
514 response->addHeader(ESPHOME_F("Private-Network-Access-ID"), get_mac_address_pretty_into_buffer(mac_s));
515 request->send(response);
516}
517#endif
518
519#ifdef USE_WEBSERVER_CSS_INCLUDE
520void WebServer::handle_css_request(AsyncWebServerRequest *request) {
521#ifndef USE_ESP8266
522 AsyncWebServerResponse *response =
523 request->beginResponse(200, "text/css", ESPHOME_WEBSERVER_CSS_INCLUDE, ESPHOME_WEBSERVER_CSS_INCLUDE_SIZE);
524#else
525 AsyncWebServerResponse *response =
526 request->beginResponse_P(200, "text/css", ESPHOME_WEBSERVER_CSS_INCLUDE, ESPHOME_WEBSERVER_CSS_INCLUDE_SIZE);
527#endif
528 response->addHeader(ESPHOME_F("Content-Encoding"), ESPHOME_F("gzip"));
529 request->send(response);
530}
531#endif
532
533#ifdef USE_WEBSERVER_JS_INCLUDE
534void WebServer::handle_js_request(AsyncWebServerRequest *request) {
535#ifndef USE_ESP8266
536 AsyncWebServerResponse *response =
537 request->beginResponse(200, "text/javascript", ESPHOME_WEBSERVER_JS_INCLUDE, ESPHOME_WEBSERVER_JS_INCLUDE_SIZE);
538#else
539 AsyncWebServerResponse *response =
540 request->beginResponse_P(200, "text/javascript", ESPHOME_WEBSERVER_JS_INCLUDE, ESPHOME_WEBSERVER_JS_INCLUDE_SIZE);
541#endif
542 response->addHeader(ESPHOME_F("Content-Encoding"), ESPHOME_F("gzip"));
543 request->send(response);
544}
545#endif
546
547// Helper functions to reduce code size by avoiding macro expansion
548// Build unique id as: {domain}/{device_name}/{entity_name} or {domain}/{entity_name}
549// Uses names (not object_id) to avoid UTF-8 collision issues
550static void set_json_id(JsonObject &root, EntityBase *obj, const char *prefix, JsonDetail start_config) {
551 const StringRef &name = obj->get_name();
552 size_t prefix_len = strlen(prefix);
553 size_t name_len = name.size();
554
555#ifdef USE_DEVICES
556 Device *device = obj->get_device();
557 const char *device_name = device ? device->get_name() : nullptr;
558 size_t device_len = device_name ? strlen(device_name) : 0;
559#endif
560
561 // Stack buffer for the id - ArduinoJson copies the string before it goes out of scope
562 // Buffer sizes use constants from entity_base.h validated in core/config.py
563 // Note: Device name uses ESPHOME_FRIENDLY_NAME_MAX_LEN (sub-device max 120), not ESPHOME_DEVICE_NAME_MAX_LEN
564 // (hostname)
565#ifdef USE_DEVICES
566 static constexpr size_t ID_BUF_SIZE =
567 ESPHOME_DOMAIN_MAX_LEN + 1 + ESPHOME_FRIENDLY_NAME_MAX_LEN + 1 + ESPHOME_FRIENDLY_NAME_MAX_LEN + 1;
568#else
569 static constexpr size_t ID_BUF_SIZE = ESPHOME_DOMAIN_MAX_LEN + 1 + ESPHOME_FRIENDLY_NAME_MAX_LEN + 1;
570#endif
571 char id_buf[ID_BUF_SIZE];
572 memcpy(id_buf, prefix, prefix_len); // NOLINT(bugprone-not-null-terminated-result)
573
574 char *p = id_buf + prefix_len;
575 *p++ = '/';
576#ifdef USE_DEVICES
577 if (device_name) {
578 memcpy(p, device_name, device_len);
579 p += device_len;
580 *p++ = '/';
581 }
582#endif
583 memcpy(p, name.c_str(), name_len);
584 p[name_len] = '\0';
585 root[ESPHOME_F("id")] = id_buf;
586
587 if (start_config == DETAIL_ALL) {
588 root[ESPHOME_F("domain")] = prefix;
589 // Use .c_str() to avoid instantiating set<StringRef> template (saves ~24B)
590 root[ESPHOME_F("name")] = name.c_str();
591#ifdef USE_DEVICES
592 if (device_name) {
593 root[ESPHOME_F("device")] = device_name;
594 }
595#endif
596#ifdef USE_ENTITY_ICON
597 char icon_buf[MAX_ICON_LENGTH];
598 root[ESPHOME_F("icon")] = obj->get_icon_to(icon_buf);
599#endif
600 root[ESPHOME_F("entity_category")] = obj->get_entity_category();
601 bool is_disabled = obj->is_disabled_by_default();
602 if (is_disabled)
603 root[ESPHOME_F("is_disabled_by_default")] = is_disabled;
604 }
605}
606
607// Keep as separate function even though only used once: reduces code size by ~48 bytes
608// by allowing compiler to share code between template instantiations (bool, float, etc.)
609template<typename T>
610static void set_json_value(JsonObject &root, EntityBase *obj, const char *prefix, const T &value,
611 JsonDetail start_config) {
612 set_json_id(root, obj, prefix, start_config);
613 root[ESPHOME_F("value")] = value;
614}
615
616template<typename S, typename T>
617static void set_json_icon_state_value(JsonObject &root, EntityBase *obj, const char *prefix, S state, const T &value,
618 JsonDetail start_config) {
619 set_json_value(root, obj, prefix, value, start_config);
620 root[ESPHOME_F("state")] = state;
621}
622
623// Helper to get request detail parameter
624[[maybe_unused]] static JsonDetail get_request_detail(AsyncWebServerRequest *request) {
625 return request->arg(ESPHOME_F("detail")) == "all" ? DETAIL_ALL : DETAIL_STATE;
626}
627
628#ifdef USE_SENSOR
630 if (!this->include_internal_ && obj->is_internal())
631 return;
632 this->events_.deferrable_send_state(obj, "state", sensor_state_json_generator);
633}
634void WebServer::handle_sensor_request(AsyncWebServerRequest *request, const UrlMatch &match) {
635 for (sensor::Sensor *obj : App.get_sensors()) {
636 auto entity_match = match.match_entity(obj);
637 if (!entity_match.matched)
638 continue;
639 // Note: request->method() is always HTTP_GET here (canHandle ensures this)
640 if (entity_match.action_is_empty) {
641 auto detail = get_request_detail(request);
642 auto data = this->sensor_json_(obj, obj->state, detail);
643 request->send(200, "application/json", data.c_str());
644 return;
645 }
646 }
647 request->send(404);
648}
650 return web_server->sensor_json_((sensor::Sensor *) (source), ((sensor::Sensor *) (source))->state, DETAIL_STATE);
651}
653 return web_server->sensor_json_((sensor::Sensor *) (source), ((sensor::Sensor *) (source))->state, DETAIL_ALL);
654}
655json::SerializationBuffer<> WebServer::sensor_json_(sensor::Sensor *obj, float value, JsonDetail start_config) {
656 json::JsonBuilder builder;
657 JsonObject root = builder.root();
658
659 const auto uom_ref = obj->get_unit_of_measurement_ref();
660 char buf[VALUE_ACCURACY_MAX_LEN];
661 const char *state = std::isnan(value)
662 ? "NA"
663 : (value_accuracy_with_uom_to_buf(buf, value, obj->get_accuracy_decimals(), uom_ref), buf);
664 set_json_icon_state_value(root, obj, "sensor", state, value, start_config);
665 if (start_config == DETAIL_ALL) {
666 this->add_sorting_info_(root, obj);
667 if (!uom_ref.empty())
668 root[ESPHOME_F("uom")] = uom_ref.c_str();
669 }
670
671 return builder.serialize();
672}
673#endif
674
675#ifdef USE_TEXT_SENSOR
677 if (!this->include_internal_ && obj->is_internal())
678 return;
679 this->events_.deferrable_send_state(obj, "state", text_sensor_state_json_generator);
680}
681void WebServer::handle_text_sensor_request(AsyncWebServerRequest *request, const UrlMatch &match) {
682 for (text_sensor::TextSensor *obj : App.get_text_sensors()) {
683 auto entity_match = match.match_entity(obj);
684 if (!entity_match.matched)
685 continue;
686 // Note: request->method() is always HTTP_GET here (canHandle ensures this)
687 if (entity_match.action_is_empty) {
688 auto detail = get_request_detail(request);
689 auto data = this->text_sensor_json_(obj, obj->state, detail);
690 request->send(200, "application/json", data.c_str());
691 return;
692 }
693 }
694 request->send(404);
695}
697 return web_server->text_sensor_json_((text_sensor::TextSensor *) (source),
699}
701 return web_server->text_sensor_json_((text_sensor::TextSensor *) (source),
702 ((text_sensor::TextSensor *) (source))->state, DETAIL_ALL);
703}
704json::SerializationBuffer<> WebServer::text_sensor_json_(text_sensor::TextSensor *obj, const std::string &value,
705 JsonDetail start_config) {
706 json::JsonBuilder builder;
707 JsonObject root = builder.root();
708
709 set_json_icon_state_value(root, obj, "text_sensor", value.c_str(), value.c_str(), start_config);
710 if (start_config == DETAIL_ALL) {
711 this->add_sorting_info_(root, obj);
712 }
713
714 return builder.serialize();
715}
716#endif
717
718#ifdef USE_SWITCH
720
721static void execute_switch_action(switch_::Switch *obj, SwitchAction action) {
722 switch (action) {
724 obj->toggle();
725 break;
727 obj->turn_on();
728 break;
730 obj->turn_off();
731 break;
732 default:
733 break;
734 }
735}
736
738 if (!this->include_internal_ && obj->is_internal())
739 return;
740 this->events_.deferrable_send_state(obj, "state", switch_state_json_generator);
741}
742void WebServer::handle_switch_request(AsyncWebServerRequest *request, const UrlMatch &match) {
743 for (switch_::Switch *obj : App.get_switches()) {
744 auto entity_match = match.match_entity(obj);
745 if (!entity_match.matched)
746 continue;
747
748 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
749 auto detail = get_request_detail(request);
750 auto data = this->switch_json_(obj, obj->state, detail);
751 request->send(200, "application/json", data.c_str());
752 return;
753 }
754
756
757 if (match.method_equals(ESPHOME_F("toggle"))) {
758 action = SWITCH_ACTION_TOGGLE;
759 } else if (match.method_equals(ESPHOME_F("turn_on"))) {
760 action = SWITCH_ACTION_TURN_ON;
761 } else if (match.method_equals(ESPHOME_F("turn_off"))) {
762 action = SWITCH_ACTION_TURN_OFF;
763 }
764
765 if (action != SWITCH_ACTION_NONE) {
766 this->defer([obj, action]() { execute_switch_action(obj, action); });
767 request->send(200);
768 } else {
769 request->send(404);
770 }
771 return;
772 }
773 request->send(404);
774}
776 return web_server->switch_json_((switch_::Switch *) (source), ((switch_::Switch *) (source))->state, DETAIL_STATE);
777}
779 return web_server->switch_json_((switch_::Switch *) (source), ((switch_::Switch *) (source))->state, DETAIL_ALL);
780}
781json::SerializationBuffer<> WebServer::switch_json_(switch_::Switch *obj, bool value, JsonDetail start_config) {
782 json::JsonBuilder builder;
783 JsonObject root = builder.root();
784
785 set_json_icon_state_value(root, obj, "switch", value ? "ON" : "OFF", value, start_config);
786 if (start_config == DETAIL_ALL) {
787 root[ESPHOME_F("assumed_state")] = obj->assumed_state();
788 this->add_sorting_info_(root, obj);
789 }
790
791 return builder.serialize();
792}
793#endif
794
795#ifdef USE_BUTTON
796void WebServer::handle_button_request(AsyncWebServerRequest *request, const UrlMatch &match) {
797 for (button::Button *obj : App.get_buttons()) {
798 auto entity_match = match.match_entity(obj);
799 if (!entity_match.matched)
800 continue;
801 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
802 auto detail = get_request_detail(request);
803 auto data = this->button_json_(obj, detail);
804 request->send(200, "application/json", data.c_str());
805 } else if (match.method_equals(ESPHOME_F("press"))) {
806 DEFER_ACTION(obj, obj->press());
807 request->send(200);
808 return;
809 } else {
810 request->send(404);
811 }
812 return;
813 }
814 request->send(404);
815}
817 return web_server->button_json_((button::Button *) (source), DETAIL_ALL);
818}
819json::SerializationBuffer<> WebServer::button_json_(button::Button *obj, JsonDetail start_config) {
820 json::JsonBuilder builder;
821 JsonObject root = builder.root();
822
823 set_json_id(root, obj, "button", start_config);
824 if (start_config == DETAIL_ALL) {
825 this->add_sorting_info_(root, obj);
826 }
827
828 return builder.serialize();
829}
830#endif
831
832#ifdef USE_BINARY_SENSOR
834 if (!this->include_internal_ && obj->is_internal())
835 return;
836 this->events_.deferrable_send_state(obj, "state", binary_sensor_state_json_generator);
837}
838void WebServer::handle_binary_sensor_request(AsyncWebServerRequest *request, const UrlMatch &match) {
839 for (binary_sensor::BinarySensor *obj : App.get_binary_sensors()) {
840 auto entity_match = match.match_entity(obj);
841 if (!entity_match.matched)
842 continue;
843 // Note: request->method() is always HTTP_GET here (canHandle ensures this)
844 if (entity_match.action_is_empty) {
845 auto detail = get_request_detail(request);
846 auto data = this->binary_sensor_json_(obj, obj->state, detail);
847 request->send(200, "application/json", data.c_str());
848 return;
849 }
850 }
851 request->send(404);
852}
854 return web_server->binary_sensor_json_((binary_sensor::BinarySensor *) (source),
856}
858 return web_server->binary_sensor_json_((binary_sensor::BinarySensor *) (source),
860}
861json::SerializationBuffer<> WebServer::binary_sensor_json_(binary_sensor::BinarySensor *obj, bool value,
862 JsonDetail start_config) {
863 json::JsonBuilder builder;
864 JsonObject root = builder.root();
865
866 set_json_icon_state_value(root, obj, "binary_sensor", value ? "ON" : "OFF", value, start_config);
867 if (start_config == DETAIL_ALL) {
868 this->add_sorting_info_(root, obj);
869 }
870
871 return builder.serialize();
872}
873#endif
874
875#ifdef USE_FAN
877 if (!this->include_internal_ && obj->is_internal())
878 return;
879 this->events_.deferrable_send_state(obj, "state", fan_state_json_generator);
880}
881void WebServer::handle_fan_request(AsyncWebServerRequest *request, const UrlMatch &match) {
882 for (fan::Fan *obj : App.get_fans()) {
883 auto entity_match = match.match_entity(obj);
884 if (!entity_match.matched)
885 continue;
886
887 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
888 auto detail = get_request_detail(request);
889 auto data = this->fan_json_(obj, detail);
890 request->send(200, "application/json", data.c_str());
891 } else if (match.method_equals(ESPHOME_F("toggle"))) {
892 DEFER_ACTION(obj, obj->toggle().perform());
893 request->send(200);
894 } else {
895 bool is_on = match.method_equals(ESPHOME_F("turn_on"));
896 bool is_off = match.method_equals(ESPHOME_F("turn_off"));
897 if (!is_on && !is_off) {
898 request->send(404);
899 return;
900 }
901 auto call = is_on ? obj->turn_on() : obj->turn_off();
902
903 parse_num_param_(request, ESPHOME_F("speed_level"), call, &decltype(call)::set_speed);
904
905 if (request->hasArg(ESPHOME_F("oscillation"))) {
906 auto speed = request->arg(ESPHOME_F("oscillation"));
907 auto val = parse_on_off(speed.c_str());
908 switch (val) {
909 case PARSE_ON:
910 call.set_oscillating(true);
911 break;
912 case PARSE_OFF:
913 call.set_oscillating(false);
914 break;
915 case PARSE_TOGGLE:
916 call.set_oscillating(!obj->oscillating);
917 break;
918 case PARSE_NONE:
919 request->send(404);
920 return;
921 }
922 }
923 DEFER_ACTION(call, call.perform());
924 request->send(200);
925 }
926 return;
927 }
928 request->send(404);
929}
931 return web_server->fan_json_((fan::Fan *) (source), DETAIL_STATE);
932}
934 return web_server->fan_json_((fan::Fan *) (source), DETAIL_ALL);
935}
936json::SerializationBuffer<> WebServer::fan_json_(fan::Fan *obj, JsonDetail start_config) {
937 json::JsonBuilder builder;
938 JsonObject root = builder.root();
939
940 set_json_icon_state_value(root, obj, "fan", obj->state ? "ON" : "OFF", obj->state, start_config);
941 const auto traits = obj->get_traits();
942 if (traits.supports_speed()) {
943 root[ESPHOME_F("speed_level")] = obj->speed;
944 root[ESPHOME_F("speed_count")] = traits.supported_speed_count();
945 }
946 if (obj->get_traits().supports_oscillation())
947 root[ESPHOME_F("oscillation")] = obj->oscillating;
948 if (start_config == DETAIL_ALL) {
949 this->add_sorting_info_(root, obj);
950 }
951
952 return builder.serialize();
953}
954#endif
955
956#ifdef USE_LIGHT
958 if (!this->include_internal_ && obj->is_internal())
959 return;
960 this->events_.deferrable_send_state(obj, "state", light_state_json_generator);
961}
962void WebServer::handle_light_request(AsyncWebServerRequest *request, const UrlMatch &match) {
963 for (light::LightState *obj : App.get_lights()) {
964 auto entity_match = match.match_entity(obj);
965 if (!entity_match.matched)
966 continue;
967
968 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
969 auto detail = get_request_detail(request);
970 auto data = this->light_json_(obj, detail);
971 request->send(200, "application/json", data.c_str());
972 } else if (match.method_equals(ESPHOME_F("toggle"))) {
973 DEFER_ACTION(obj, obj->toggle().perform());
974 request->send(200);
975 } else {
976 bool is_on = match.method_equals(ESPHOME_F("turn_on"));
977 bool is_off = match.method_equals(ESPHOME_F("turn_off"));
978 if (!is_on && !is_off) {
979 request->send(404);
980 return;
981 }
982 auto call = is_on ? obj->turn_on() : obj->turn_off();
983
984 if (is_on) {
985 // Parse color parameters
986 parse_light_param_(request, ESPHOME_F("brightness"), call, &decltype(call)::set_brightness, 255.0f);
987 parse_light_param_(request, ESPHOME_F("r"), call, &decltype(call)::set_red, 255.0f);
988 parse_light_param_(request, ESPHOME_F("g"), call, &decltype(call)::set_green, 255.0f);
989 parse_light_param_(request, ESPHOME_F("b"), call, &decltype(call)::set_blue, 255.0f);
990 parse_light_param_(request, ESPHOME_F("white_value"), call, &decltype(call)::set_white, 255.0f);
991 parse_light_param_(request, ESPHOME_F("color_temp"), call, &decltype(call)::set_color_temperature);
992
993 // Parse timing parameters
994 parse_light_param_uint_(request, ESPHOME_F("flash"), call, &decltype(call)::set_flash_length, 1000);
995 }
996 parse_light_param_uint_(request, ESPHOME_F("transition"), call, &decltype(call)::set_transition_length, 1000);
997
998 if (is_on) {
1000 request, ESPHOME_F("effect"), call,
1001 static_cast<light::LightCall &(light::LightCall::*) (const char *, size_t)>(&decltype(call)::set_effect));
1002 }
1003
1004 DEFER_ACTION(call, call.perform());
1005 request->send(200);
1006 }
1007 return;
1008 }
1009 request->send(404);
1010}
1012 return web_server->light_json_((light::LightState *) (source), DETAIL_STATE);
1013}
1015 return web_server->light_json_((light::LightState *) (source), DETAIL_ALL);
1016}
1017json::SerializationBuffer<> WebServer::light_json_(light::LightState *obj, JsonDetail start_config) {
1018 json::JsonBuilder builder;
1019 JsonObject root = builder.root();
1020
1021 set_json_value(root, obj, "light", obj->remote_values.is_on() ? "ON" : "OFF", start_config);
1022
1024 if (start_config == DETAIL_ALL) {
1025 JsonArray opt = root[ESPHOME_F("effects")].to<JsonArray>();
1026 opt.add("None");
1027 for (auto const &option : obj->get_effects()) {
1028 opt.add(option->get_name());
1029 }
1030 this->add_sorting_info_(root, obj);
1031 }
1032
1033 return builder.serialize();
1034}
1035#endif
1036
1037#ifdef USE_COVER
1039 if (!this->include_internal_ && obj->is_internal())
1040 return;
1041 this->events_.deferrable_send_state(obj, "state", cover_state_json_generator);
1042}
1043void WebServer::handle_cover_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1044 for (cover::Cover *obj : App.get_covers()) {
1045 auto entity_match = match.match_entity(obj);
1046 if (!entity_match.matched)
1047 continue;
1048
1049 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1050 auto detail = get_request_detail(request);
1051 auto data = this->cover_json_(obj, detail);
1052 request->send(200, "application/json", data.c_str());
1053 return;
1054 }
1055
1056 auto call = obj->make_call();
1057
1058 // Lookup table for cover methods
1059 static const struct {
1060 const char *name;
1061 cover::CoverCall &(cover::CoverCall::*action)();
1062 } METHODS[] = {
1067 };
1068
1069 bool found = false;
1070 for (const auto &method : METHODS) {
1071 if (match.method_equals(method.name)) {
1072 (call.*method.action)();
1073 found = true;
1074 break;
1075 }
1076 }
1077
1078 if (!found && !match.method_equals(ESPHOME_F("set"))) {
1079 request->send(404);
1080 return;
1081 }
1082
1083 auto traits = obj->get_traits();
1084 if ((request->hasArg(ESPHOME_F("position")) && !traits.get_supports_position()) ||
1085 (request->hasArg(ESPHOME_F("tilt")) && !traits.get_supports_tilt())) {
1086 request->send(409);
1087 return;
1088 }
1089
1090 parse_num_param_(request, ESPHOME_F("position"), call, &decltype(call)::set_position);
1091 parse_num_param_(request, ESPHOME_F("tilt"), call, &decltype(call)::set_tilt);
1092
1093 DEFER_ACTION(call, call.perform());
1094 request->send(200);
1095 return;
1096 }
1097 request->send(404);
1098}
1100 return web_server->cover_json_((cover::Cover *) (source), DETAIL_STATE);
1101}
1103 return web_server->cover_json_((cover::Cover *) (source), DETAIL_ALL);
1104}
1105json::SerializationBuffer<> WebServer::cover_json_(cover::Cover *obj, JsonDetail start_config) {
1106 json::JsonBuilder builder;
1107 JsonObject root = builder.root();
1108
1109 set_json_icon_state_value(root, obj, "cover", obj->is_fully_closed() ? "CLOSED" : "OPEN", obj->position,
1110 start_config);
1111 root[ESPHOME_F("current_operation")] = json_state_str(cover::cover_operation_to_str(obj->current_operation));
1112
1113 if (obj->get_traits().get_supports_position())
1114 root[ESPHOME_F("position")] = obj->position;
1115 if (obj->get_traits().get_supports_tilt())
1116 root[ESPHOME_F("tilt")] = obj->tilt;
1117 if (start_config == DETAIL_ALL) {
1118 root[ESPHOME_F("assumed_state")] = obj->get_traits().get_is_assumed_state();
1119 this->add_sorting_info_(root, obj);
1120 }
1121
1122 return builder.serialize();
1123}
1124#endif
1125
1126#ifdef USE_NUMBER
1128 if (!this->include_internal_ && obj->is_internal())
1129 return;
1130 this->events_.deferrable_send_state(obj, "state", number_state_json_generator);
1131}
1132void WebServer::handle_number_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1133 for (auto *obj : App.get_numbers()) {
1134 auto entity_match = match.match_entity(obj);
1135 if (!entity_match.matched)
1136 continue;
1137
1138 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1139 auto detail = get_request_detail(request);
1140 auto data = this->number_json_(obj, obj->state, detail);
1141 request->send(200, "application/json", data.c_str());
1142 return;
1143 }
1144 if (!match.method_equals(ESPHOME_F("set"))) {
1145 request->send(404);
1146 return;
1147 }
1148
1149 auto call = obj->make_call();
1150 parse_num_param_(request, ESPHOME_F("value"), call, &decltype(call)::set_value);
1151
1152 DEFER_ACTION(call, call.perform());
1153 request->send(200);
1154 return;
1155 }
1156 request->send(404);
1157}
1158
1160 return web_server->number_json_((number::Number *) (source), ((number::Number *) (source))->state, DETAIL_STATE);
1161}
1163 return web_server->number_json_((number::Number *) (source), ((number::Number *) (source))->state, DETAIL_ALL);
1164}
1165json::SerializationBuffer<> WebServer::number_json_(number::Number *obj, float value, JsonDetail start_config) {
1166 json::JsonBuilder builder;
1167 JsonObject root = builder.root();
1168
1169 const auto uom_ref = obj->get_unit_of_measurement_ref();
1170 const int8_t accuracy = step_to_accuracy_decimals(obj->traits.get_step());
1171
1172 // Need two buffers: one for value, one for state with UOM
1173 char val_buf[VALUE_ACCURACY_MAX_LEN];
1174 char state_buf[VALUE_ACCURACY_MAX_LEN];
1175 const char *val_str = std::isnan(value) ? "\"NaN\"" : (value_accuracy_to_buf(val_buf, value, accuracy), val_buf);
1176 const char *state_str =
1177 std::isnan(value) ? "NA" : (value_accuracy_with_uom_to_buf(state_buf, value, accuracy, uom_ref), state_buf);
1178 set_json_icon_state_value(root, obj, "number", state_str, val_str, start_config);
1179 if (start_config == DETAIL_ALL) {
1180 // ArduinoJson copies the string immediately, so we can reuse val_buf
1181 root[ESPHOME_F("min_value")] = (value_accuracy_to_buf(val_buf, obj->traits.get_min_value(), accuracy), val_buf);
1182 root[ESPHOME_F("max_value")] = (value_accuracy_to_buf(val_buf, obj->traits.get_max_value(), accuracy), val_buf);
1183 root[ESPHOME_F("step")] = (value_accuracy_to_buf(val_buf, obj->traits.get_step(), accuracy), val_buf);
1184 root[ESPHOME_F("mode")] = (int) obj->traits.get_mode();
1185 if (!uom_ref.empty())
1186 root[ESPHOME_F("uom")] = uom_ref.c_str();
1187 this->add_sorting_info_(root, obj);
1188 }
1189
1190 return builder.serialize();
1191}
1192#endif
1193
1194#ifdef USE_DATETIME_DATE
1196 if (!this->include_internal_ && obj->is_internal())
1197 return;
1198 this->events_.deferrable_send_state(obj, "state", date_state_json_generator);
1199}
1200void WebServer::handle_date_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1201 for (auto *obj : App.get_dates()) {
1202 auto entity_match = match.match_entity(obj);
1203 if (!entity_match.matched)
1204 continue;
1205 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1206 auto detail = get_request_detail(request);
1207 auto data = this->date_json_(obj, detail);
1208 request->send(200, "application/json", data.c_str());
1209 return;
1210 }
1211 if (!match.method_equals(ESPHOME_F("set"))) {
1212 request->send(404);
1213 return;
1214 }
1215
1216 auto call = obj->make_call();
1217
1218 const auto &value = request->arg(ESPHOME_F("value"));
1219 // Arduino String has isEmpty() not empty(), use length() for cross-platform compatibility
1220 if (value.length() == 0) { // NOLINT(readability-container-size-empty)
1221 request->send(409);
1222 return;
1223 }
1224 call.set_date(value.c_str(), value.length());
1225
1226 DEFER_ACTION(call, call.perform());
1227 request->send(200);
1228 return;
1229 }
1230 request->send(404);
1231}
1232
1234 return web_server->date_json_((datetime::DateEntity *) (source), DETAIL_STATE);
1235}
1237 return web_server->date_json_((datetime::DateEntity *) (source), DETAIL_ALL);
1238}
1239json::SerializationBuffer<> WebServer::date_json_(datetime::DateEntity *obj, JsonDetail start_config) {
1240 json::JsonBuilder builder;
1241 JsonObject root = builder.root();
1242
1243 // Format: YYYY-MM-DD (max 10 chars + null)
1244 char value[12];
1245 buf_append_printf(value, sizeof(value), 0, "%d-%02d-%02d", obj->year, obj->month, obj->day);
1246 set_json_icon_state_value(root, obj, "date", value, value, start_config);
1247 if (start_config == DETAIL_ALL) {
1248 this->add_sorting_info_(root, obj);
1249 }
1250
1251 return builder.serialize();
1252}
1253#endif // USE_DATETIME_DATE
1254
1255#ifdef USE_DATETIME_TIME
1257 if (!this->include_internal_ && obj->is_internal())
1258 return;
1259 this->events_.deferrable_send_state(obj, "state", time_state_json_generator);
1260}
1261void WebServer::handle_time_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1262 for (auto *obj : App.get_times()) {
1263 auto entity_match = match.match_entity(obj);
1264 if (!entity_match.matched)
1265 continue;
1266 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1267 auto detail = get_request_detail(request);
1268 auto data = this->time_json_(obj, detail);
1269 request->send(200, "application/json", data.c_str());
1270 return;
1271 }
1272 if (!match.method_equals(ESPHOME_F("set"))) {
1273 request->send(404);
1274 return;
1275 }
1276
1277 auto call = obj->make_call();
1278
1279 const auto &value = request->arg(ESPHOME_F("value"));
1280 // Arduino String has isEmpty() not empty(), use length() for cross-platform compatibility
1281 if (value.length() == 0) { // NOLINT(readability-container-size-empty)
1282 request->send(409);
1283 return;
1284 }
1285 call.set_time(value.c_str(), value.length());
1286
1287 DEFER_ACTION(call, call.perform());
1288 request->send(200);
1289 return;
1290 }
1291 request->send(404);
1292}
1294 return web_server->time_json_((datetime::TimeEntity *) (source), DETAIL_STATE);
1295}
1297 return web_server->time_json_((datetime::TimeEntity *) (source), DETAIL_ALL);
1298}
1299json::SerializationBuffer<> WebServer::time_json_(datetime::TimeEntity *obj, JsonDetail start_config) {
1300 json::JsonBuilder builder;
1301 JsonObject root = builder.root();
1302
1303 // Format: HH:MM:SS (8 chars + null)
1304 char value[12];
1305 buf_append_printf(value, sizeof(value), 0, "%02d:%02d:%02d", obj->hour, obj->minute, obj->second);
1306 set_json_icon_state_value(root, obj, "time", value, value, start_config);
1307 if (start_config == DETAIL_ALL) {
1308 this->add_sorting_info_(root, obj);
1309 }
1310
1311 return builder.serialize();
1312}
1313#endif // USE_DATETIME_TIME
1314
1315#ifdef USE_DATETIME_DATETIME
1317 if (!this->include_internal_ && obj->is_internal())
1318 return;
1319 this->events_.deferrable_send_state(obj, "state", datetime_state_json_generator);
1320}
1321void WebServer::handle_datetime_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1322 for (auto *obj : App.get_datetimes()) {
1323 auto entity_match = match.match_entity(obj);
1324 if (!entity_match.matched)
1325 continue;
1326 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1327 auto detail = get_request_detail(request);
1328 auto data = this->datetime_json_(obj, detail);
1329 request->send(200, "application/json", data.c_str());
1330 return;
1331 }
1332 if (!match.method_equals(ESPHOME_F("set"))) {
1333 request->send(404);
1334 return;
1335 }
1336
1337 auto call = obj->make_call();
1338
1339 const auto &value = request->arg(ESPHOME_F("value"));
1340 // Arduino String has isEmpty() not empty(), use length() for cross-platform compatibility
1341 if (value.length() == 0) { // NOLINT(readability-container-size-empty)
1342 request->send(409);
1343 return;
1344 }
1345 call.set_datetime(value.c_str(), value.length());
1346
1347 DEFER_ACTION(call, call.perform());
1348 request->send(200);
1349 return;
1350 }
1351 request->send(404);
1352}
1354 return web_server->datetime_json_((datetime::DateTimeEntity *) (source), DETAIL_STATE);
1355}
1357 return web_server->datetime_json_((datetime::DateTimeEntity *) (source), DETAIL_ALL);
1358}
1359json::SerializationBuffer<> WebServer::datetime_json_(datetime::DateTimeEntity *obj, JsonDetail start_config) {
1360 json::JsonBuilder builder;
1361 JsonObject root = builder.root();
1362
1363 // Format: YYYY-MM-DD HH:MM:SS (max 19 chars + null)
1364 char value[24];
1365 buf_append_printf(value, sizeof(value), 0, "%d-%02d-%02d %02d:%02d:%02d", obj->year, obj->month, obj->day, obj->hour,
1366 obj->minute, obj->second);
1367 set_json_icon_state_value(root, obj, "datetime", value, value, start_config);
1368 if (start_config == DETAIL_ALL) {
1369 this->add_sorting_info_(root, obj);
1370 }
1371
1372 return builder.serialize();
1373}
1374#endif // USE_DATETIME_DATETIME
1375
1376#ifdef USE_TEXT
1378 if (!this->include_internal_ && obj->is_internal())
1379 return;
1380 this->events_.deferrable_send_state(obj, "state", text_state_json_generator);
1381}
1382void WebServer::handle_text_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1383 for (auto *obj : App.get_texts()) {
1384 auto entity_match = match.match_entity(obj);
1385 if (!entity_match.matched)
1386 continue;
1387
1388 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1389 auto detail = get_request_detail(request);
1390 auto data = this->text_json_(obj, obj->state, detail);
1391 request->send(200, "application/json", data.c_str());
1392 return;
1393 }
1394 if (!match.method_equals(ESPHOME_F("set"))) {
1395 request->send(404);
1396 return;
1397 }
1398
1399 auto call = obj->make_call();
1401 request, ESPHOME_F("value"), call,
1402 static_cast<text::TextCall &(text::TextCall::*) (const char *, size_t)>(&decltype(call)::set_value));
1403
1404 DEFER_ACTION(call, call.perform());
1405 request->send(200);
1406 return;
1407 }
1408 request->send(404);
1409}
1410
1412 return web_server->text_json_((text::Text *) (source), ((text::Text *) (source))->state, DETAIL_STATE);
1413}
1415 return web_server->text_json_((text::Text *) (source), ((text::Text *) (source))->state, DETAIL_ALL);
1416}
1417json::SerializationBuffer<> WebServer::text_json_(text::Text *obj, const std::string &value, JsonDetail start_config) {
1418 json::JsonBuilder builder;
1419 JsonObject root = builder.root();
1420
1421 const char *state = obj->traits.get_mode() == text::TextMode::TEXT_MODE_PASSWORD ? "********" : value.c_str();
1422 set_json_icon_state_value(root, obj, "text", state, value.c_str(), start_config);
1423 root[ESPHOME_F("min_length")] = obj->traits.get_min_length();
1424 root[ESPHOME_F("max_length")] = obj->traits.get_max_length();
1425 root[ESPHOME_F("pattern")] = obj->traits.get_pattern_c_str();
1426 if (start_config == DETAIL_ALL) {
1427 root[ESPHOME_F("mode")] = (int) obj->traits.get_mode();
1428 this->add_sorting_info_(root, obj);
1429 }
1430
1431 return builder.serialize();
1432}
1433#endif
1434
1435#ifdef USE_SELECT
1437 if (!this->include_internal_ && obj->is_internal())
1438 return;
1439 this->events_.deferrable_send_state(obj, "state", select_state_json_generator);
1440}
1441void WebServer::handle_select_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1442 for (auto *obj : App.get_selects()) {
1443 auto entity_match = match.match_entity(obj);
1444 if (!entity_match.matched)
1445 continue;
1446
1447 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1448 auto detail = get_request_detail(request);
1449 auto data = this->select_json_(obj, obj->has_state() ? obj->current_option() : StringRef(), detail);
1450 request->send(200, "application/json", data.c_str());
1451 return;
1452 }
1453
1454 if (!match.method_equals(ESPHOME_F("set"))) {
1455 request->send(404);
1456 return;
1457 }
1458
1459 auto call = obj->make_call();
1461 request, ESPHOME_F("option"), call,
1462 static_cast<select::SelectCall &(select::SelectCall::*) (const char *, size_t)>(&decltype(call)::set_option));
1463
1464 DEFER_ACTION(call, call.perform());
1465 request->send(200);
1466 return;
1467 }
1468 request->send(404);
1469}
1471 auto *obj = (select::Select *) (source);
1472 return web_server->select_json_(obj, obj->has_state() ? obj->current_option() : StringRef(), DETAIL_STATE);
1473}
1475 auto *obj = (select::Select *) (source);
1476 return web_server->select_json_(obj, obj->has_state() ? obj->current_option() : StringRef(), DETAIL_ALL);
1477}
1478json::SerializationBuffer<> WebServer::select_json_(select::Select *obj, StringRef value, JsonDetail start_config) {
1479 json::JsonBuilder builder;
1480 JsonObject root = builder.root();
1481
1482 // value points to null-terminated string literals from codegen (via current_option())
1483 set_json_icon_state_value(root, obj, "select", value.c_str(), value.c_str(), start_config);
1484 if (start_config == DETAIL_ALL) {
1485 JsonArray opt = root[ESPHOME_F("option")].to<JsonArray>();
1486 for (auto &option : obj->traits.get_options()) {
1487 opt.add(option);
1488 }
1489 this->add_sorting_info_(root, obj);
1490 }
1491
1492 return builder.serialize();
1493}
1494#endif
1495
1496#ifdef USE_CLIMATE
1498 if (!this->include_internal_ && obj->is_internal())
1499 return;
1500 this->events_.deferrable_send_state(obj, "state", climate_state_json_generator);
1501}
1502void WebServer::handle_climate_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1503 for (auto *obj : App.get_climates()) {
1504 auto entity_match = match.match_entity(obj);
1505 if (!entity_match.matched)
1506 continue;
1507
1508 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1509 auto detail = get_request_detail(request);
1510 auto data = this->climate_json_(obj, detail);
1511 request->send(200, "application/json", data.c_str());
1512 return;
1513 }
1514
1515 if (!match.method_equals(ESPHOME_F("set"))) {
1516 request->send(404);
1517 return;
1518 }
1519
1520 auto call = obj->make_call();
1521
1522 // Parse string mode parameters
1524 request, ESPHOME_F("mode"), call,
1525 static_cast<climate::ClimateCall &(climate::ClimateCall::*) (const char *, size_t)>(&decltype(call)::set_mode));
1526 parse_cstr_param_(request, ESPHOME_F("fan_mode"), call,
1527 static_cast<climate::ClimateCall &(climate::ClimateCall::*) (const char *, size_t)>(
1528 &decltype(call)::set_fan_mode));
1529 parse_cstr_param_(request, ESPHOME_F("swing_mode"), call,
1530 static_cast<climate::ClimateCall &(climate::ClimateCall::*) (const char *, size_t)>(
1531 &decltype(call)::set_swing_mode));
1532 parse_cstr_param_(request, ESPHOME_F("preset"), call,
1533 static_cast<climate::ClimateCall &(climate::ClimateCall::*) (const char *, size_t)>(
1534 &decltype(call)::set_preset));
1535
1536 // Parse temperature parameters
1537 // static_cast needed to disambiguate overloaded setters (float vs optional<float>)
1538 using ClimateCall = decltype(call);
1539 parse_num_param_(request, ESPHOME_F("target_temperature_high"), call,
1540 static_cast<ClimateCall &(ClimateCall::*) (float)>(&ClimateCall::set_target_temperature_high));
1541 parse_num_param_(request, ESPHOME_F("target_temperature_low"), call,
1542 static_cast<ClimateCall &(ClimateCall::*) (float)>(&ClimateCall::set_target_temperature_low));
1543 parse_num_param_(request, ESPHOME_F("target_temperature"), call,
1544 static_cast<ClimateCall &(ClimateCall::*) (float)>(&ClimateCall::set_target_temperature));
1545
1546 DEFER_ACTION(call, call.perform());
1547 request->send(200);
1548 return;
1549 }
1550 request->send(404);
1551}
1553 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
1554 return web_server->climate_json_((climate::Climate *) (source), DETAIL_STATE);
1555}
1557 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
1558 return web_server->climate_json_((climate::Climate *) (source), DETAIL_ALL);
1559}
1560json::SerializationBuffer<> WebServer::climate_json_(climate::Climate *obj, JsonDetail start_config) {
1561 // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
1562 json::JsonBuilder builder;
1563 JsonObject root = builder.root();
1564 set_json_id(root, obj, "climate", start_config);
1565 const auto traits = obj->get_traits();
1566 int8_t target_accuracy = traits.get_target_temperature_accuracy_decimals();
1567 int8_t current_accuracy = traits.get_current_temperature_accuracy_decimals();
1568 char temp_buf[VALUE_ACCURACY_MAX_LEN];
1569
1570 if (start_config == DETAIL_ALL) {
1571 JsonArray opt = root[ESPHOME_F("modes")].to<JsonArray>();
1572 for (climate::ClimateMode m : traits.get_supported_modes())
1573 opt.add(json_state_str(climate::climate_mode_to_string(m)));
1574 if (traits.get_supports_fan_modes()) {
1575 JsonArray opt = root[ESPHOME_F("fan_modes")].to<JsonArray>();
1576 for (climate::ClimateFanMode m : traits.get_supported_fan_modes())
1577 opt.add(json_state_str(climate::climate_fan_mode_to_string(m)));
1578 }
1579
1580 if (!traits.get_supported_custom_fan_modes().empty()) {
1581 JsonArray opt = root[ESPHOME_F("custom_fan_modes")].to<JsonArray>();
1582 for (auto const &custom_fan_mode : traits.get_supported_custom_fan_modes())
1583 opt.add(custom_fan_mode);
1584 }
1585 if (traits.get_supports_swing_modes()) {
1586 JsonArray opt = root[ESPHOME_F("swing_modes")].to<JsonArray>();
1587 for (auto swing_mode : traits.get_supported_swing_modes())
1588 opt.add(json_state_str(climate::climate_swing_mode_to_string(swing_mode)));
1589 }
1590 if (traits.get_supports_presets()) {
1591 JsonArray opt = root[ESPHOME_F("presets")].to<JsonArray>();
1592 for (climate::ClimatePreset m : traits.get_supported_presets())
1593 opt.add(json_state_str(climate::climate_preset_to_string(m)));
1594 }
1595 if (!traits.get_supported_custom_presets().empty()) {
1596 JsonArray opt = root[ESPHOME_F("custom_presets")].to<JsonArray>();
1597 for (auto const &custom_preset : traits.get_supported_custom_presets())
1598 opt.add(custom_preset);
1599 }
1600 root[ESPHOME_F("max_temp")] =
1601 (value_accuracy_to_buf(temp_buf, traits.get_visual_max_temperature(), target_accuracy), temp_buf);
1602 root[ESPHOME_F("min_temp")] =
1603 (value_accuracy_to_buf(temp_buf, traits.get_visual_min_temperature(), target_accuracy), temp_buf);
1604 root[ESPHOME_F("step")] = traits.get_visual_target_temperature_step();
1605 this->add_sorting_info_(root, obj);
1606 }
1607
1608 bool has_state = false;
1609 root[ESPHOME_F("mode")] = json_state_str(climate_mode_to_string(obj->mode));
1610 if (traits.has_feature_flags(climate::CLIMATE_SUPPORTS_ACTION)) {
1611 root[ESPHOME_F("action")] = json_state_str(climate_action_to_string(obj->action));
1612 root[ESPHOME_F("state")] = root[ESPHOME_F("action")];
1613 has_state = true;
1614 }
1615 if (traits.get_supports_fan_modes() && obj->fan_mode.has_value()) {
1616 root[ESPHOME_F("fan_mode")] = json_state_str(climate_fan_mode_to_string(obj->fan_mode.value()));
1617 }
1618 if (!traits.get_supported_custom_fan_modes().empty() && obj->has_custom_fan_mode()) {
1619 root[ESPHOME_F("custom_fan_mode")] = obj->get_custom_fan_mode();
1620 }
1621 if (traits.get_supports_presets() && obj->preset.has_value()) {
1622 root[ESPHOME_F("preset")] = json_state_str(climate_preset_to_string(obj->preset.value()));
1623 }
1624 if (!traits.get_supported_custom_presets().empty() && obj->has_custom_preset()) {
1625 root[ESPHOME_F("custom_preset")] = obj->get_custom_preset();
1626 }
1627 if (traits.get_supports_swing_modes()) {
1628 root[ESPHOME_F("swing_mode")] = json_state_str(climate_swing_mode_to_string(obj->swing_mode));
1629 }
1630 if (traits.has_feature_flags(climate::CLIMATE_SUPPORTS_CURRENT_TEMPERATURE)) {
1631 root[ESPHOME_F("current_temperature")] =
1632 std::isnan(obj->current_temperature)
1633 ? "NA"
1634 : (value_accuracy_to_buf(temp_buf, obj->current_temperature, current_accuracy), temp_buf);
1635 }
1636 if (traits.has_feature_flags(climate::CLIMATE_SUPPORTS_CURRENT_HUMIDITY)) {
1637 root[ESPHOME_F("current_humidity")] = std::isnan(obj->current_humidity)
1638 ? "NA"
1639 : (value_accuracy_to_buf(temp_buf, obj->current_humidity, 0), temp_buf);
1640 }
1641 if (traits.has_feature_flags(climate::CLIMATE_SUPPORTS_TWO_POINT_TARGET_TEMPERATURE |
1643 root[ESPHOME_F("target_temperature_low")] =
1644 (value_accuracy_to_buf(temp_buf, obj->target_temperature_low, target_accuracy), temp_buf);
1645 root[ESPHOME_F("target_temperature_high")] =
1646 (value_accuracy_to_buf(temp_buf, obj->target_temperature_high, target_accuracy), temp_buf);
1647 if (!has_state) {
1648 root[ESPHOME_F("state")] =
1650 target_accuracy),
1651 temp_buf);
1652 }
1653 } else {
1654 root[ESPHOME_F("target_temperature")] =
1655 (value_accuracy_to_buf(temp_buf, obj->target_temperature, target_accuracy), temp_buf);
1656 if (!has_state)
1657 root[ESPHOME_F("state")] = root[ESPHOME_F("target_temperature")];
1658 }
1659
1660 return builder.serialize();
1661 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
1662}
1663#endif
1664
1665#ifdef USE_LOCK
1667
1668static void execute_lock_action(lock::Lock *obj, LockAction action) {
1669 switch (action) {
1670 case LOCK_ACTION_LOCK:
1671 obj->lock();
1672 break;
1673 case LOCK_ACTION_UNLOCK:
1674 obj->unlock();
1675 break;
1676 case LOCK_ACTION_OPEN:
1677 obj->open();
1678 break;
1679 default:
1680 break;
1681 }
1682}
1683
1685 if (!this->include_internal_ && obj->is_internal())
1686 return;
1687 this->events_.deferrable_send_state(obj, "state", lock_state_json_generator);
1688}
1689void WebServer::handle_lock_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1690 for (lock::Lock *obj : App.get_locks()) {
1691 auto entity_match = match.match_entity(obj);
1692 if (!entity_match.matched)
1693 continue;
1694
1695 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1696 auto detail = get_request_detail(request);
1697 auto data = this->lock_json_(obj, obj->state, detail);
1698 request->send(200, "application/json", data.c_str());
1699 return;
1700 }
1701
1703
1704 if (match.method_equals(ESPHOME_F("lock"))) {
1705 action = LOCK_ACTION_LOCK;
1706 } else if (match.method_equals(ESPHOME_F("unlock"))) {
1707 action = LOCK_ACTION_UNLOCK;
1708 } else if (match.method_equals(ESPHOME_F("open"))) {
1709 action = LOCK_ACTION_OPEN;
1710 }
1711
1712 if (action != LOCK_ACTION_NONE) {
1713 this->defer([obj, action]() { execute_lock_action(obj, action); });
1714 request->send(200);
1715 } else {
1716 request->send(404);
1717 }
1718 return;
1719 }
1720 request->send(404);
1721}
1723 return web_server->lock_json_((lock::Lock *) (source), ((lock::Lock *) (source))->state, DETAIL_STATE);
1724}
1726 return web_server->lock_json_((lock::Lock *) (source), ((lock::Lock *) (source))->state, DETAIL_ALL);
1727}
1728json::SerializationBuffer<> WebServer::lock_json_(lock::Lock *obj, lock::LockState value, JsonDetail start_config) {
1729 json::JsonBuilder builder;
1730 JsonObject root = builder.root();
1731
1732 set_json_icon_state_value(root, obj, "lock", json_state_str(lock::lock_state_to_string(value)), value, start_config);
1733 if (start_config == DETAIL_ALL) {
1734 this->add_sorting_info_(root, obj);
1735 }
1736
1737 return builder.serialize();
1738}
1739#endif
1740
1741#ifdef USE_VALVE
1743 if (!this->include_internal_ && obj->is_internal())
1744 return;
1745 this->events_.deferrable_send_state(obj, "state", valve_state_json_generator);
1746}
1747void WebServer::handle_valve_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1748 for (valve::Valve *obj : App.get_valves()) {
1749 auto entity_match = match.match_entity(obj);
1750 if (!entity_match.matched)
1751 continue;
1752
1753 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1754 auto detail = get_request_detail(request);
1755 auto data = this->valve_json_(obj, detail);
1756 request->send(200, "application/json", data.c_str());
1757 return;
1758 }
1759
1760 auto call = obj->make_call();
1761
1762 // Lookup table for valve methods
1763 static const struct {
1764 const char *name;
1765 valve::ValveCall &(valve::ValveCall::*action)();
1766 } METHODS[] = {
1771 };
1772
1773 bool found = false;
1774 for (const auto &method : METHODS) {
1775 if (match.method_equals(method.name)) {
1776 (call.*method.action)();
1777 found = true;
1778 break;
1779 }
1780 }
1781
1782 if (!found && !match.method_equals(ESPHOME_F("set"))) {
1783 request->send(404);
1784 return;
1785 }
1786
1787 auto traits = obj->get_traits();
1788 if (request->hasArg(ESPHOME_F("position")) && !traits.get_supports_position()) {
1789 request->send(409);
1790 return;
1791 }
1792
1793 parse_num_param_(request, ESPHOME_F("position"), call, &decltype(call)::set_position);
1794
1795 DEFER_ACTION(call, call.perform());
1796 request->send(200);
1797 return;
1798 }
1799 request->send(404);
1800}
1802 return web_server->valve_json_((valve::Valve *) (source), DETAIL_STATE);
1803}
1805 return web_server->valve_json_((valve::Valve *) (source), DETAIL_ALL);
1806}
1807json::SerializationBuffer<> WebServer::valve_json_(valve::Valve *obj, JsonDetail start_config) {
1808 json::JsonBuilder builder;
1809 JsonObject root = builder.root();
1810
1811 set_json_icon_state_value(root, obj, "valve", obj->is_fully_closed() ? "CLOSED" : "OPEN", obj->position,
1812 start_config);
1813 root[ESPHOME_F("current_operation")] = json_state_str(valve::valve_operation_to_str(obj->current_operation));
1814
1815 if (obj->get_traits().get_supports_position())
1816 root[ESPHOME_F("position")] = obj->position;
1817 if (start_config == DETAIL_ALL) {
1818 this->add_sorting_info_(root, obj);
1819 }
1820
1821 return builder.serialize();
1822}
1823#endif
1824
1825#ifdef USE_ALARM_CONTROL_PANEL
1827 if (!this->include_internal_ && obj->is_internal())
1828 return;
1829 this->events_.deferrable_send_state(obj, "state", alarm_control_panel_state_json_generator);
1830}
1831void WebServer::handle_alarm_control_panel_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1832 for (alarm_control_panel::AlarmControlPanel *obj : App.get_alarm_control_panels()) {
1833 auto entity_match = match.match_entity(obj);
1834 if (!entity_match.matched)
1835 continue;
1836
1837 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1838 auto detail = get_request_detail(request);
1839 auto data = this->alarm_control_panel_json_(obj, obj->get_state(), detail);
1840 request->send(200, "application/json", data.c_str());
1841 return;
1842 }
1843
1844 auto call = obj->make_call();
1846 request, ESPHOME_F("code"), call,
1848 alarm_control_panel::AlarmControlPanelCall::*) (const char *, size_t)>(&decltype(call)::set_code));
1849
1850 // Lookup table for alarm control panel methods
1851 static const struct {
1852 const char *name;
1854 } METHODS[] = {
1860 };
1861
1862 bool found = false;
1863 for (const auto &method : METHODS) {
1864 if (match.method_equals(method.name)) {
1865 (call.*method.action)();
1866 found = true;
1867 break;
1868 }
1869 }
1870
1871 if (!found) {
1872 request->send(404);
1873 return;
1874 }
1875
1876 DEFER_ACTION(call, call.perform());
1877 request->send(200);
1878 return;
1879 }
1880 request->send(404);
1881}
1883 return web_server->alarm_control_panel_json_((alarm_control_panel::AlarmControlPanel *) (source),
1884 ((alarm_control_panel::AlarmControlPanel *) (source))->get_state(),
1885 DETAIL_STATE);
1886}
1888 return web_server->alarm_control_panel_json_((alarm_control_panel::AlarmControlPanel *) (source),
1889 ((alarm_control_panel::AlarmControlPanel *) (source))->get_state(),
1890 DETAIL_ALL);
1891}
1892json::SerializationBuffer<> WebServer::alarm_control_panel_json_(alarm_control_panel::AlarmControlPanel *obj,
1894 JsonDetail start_config) {
1895 json::JsonBuilder builder;
1896 JsonObject root = builder.root();
1897
1898 set_json_icon_state_value(root, obj, "alarm_control_panel",
1899 json_state_str(alarm_control_panel_state_to_string(value)), value, start_config);
1900 if (start_config == DETAIL_ALL) {
1901 this->add_sorting_info_(root, obj);
1902 }
1903
1904 return builder.serialize();
1905}
1906#endif
1907
1908#ifdef USE_WATER_HEATER
1910 if (!this->include_internal_ && obj->is_internal())
1911 return;
1912 this->events_.deferrable_send_state(obj, "state", water_heater_state_json_generator);
1913}
1914void WebServer::handle_water_heater_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1915 for (water_heater::WaterHeater *obj : App.get_water_heaters()) {
1916 auto entity_match = match.match_entity(obj);
1917 if (!entity_match.matched)
1918 continue;
1919
1920 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1921 auto detail = get_request_detail(request);
1922 auto data = this->water_heater_json_(obj, detail);
1923 request->send(200, "application/json", data.c_str());
1924 return;
1925 }
1926 if (!match.method_equals(ESPHOME_F("set"))) {
1927 request->send(404);
1928 return;
1929 }
1930 auto call = obj->make_call();
1931 // Use base class reference for template deduction (make_call returns WaterHeaterCallInternal)
1933
1934 // Parse mode parameter
1936 request, ESPHOME_F("mode"), base_call,
1937 static_cast<water_heater::WaterHeaterCall &(water_heater::WaterHeaterCall::*) (const char *, size_t)>(
1939
1940 // Parse temperature parameters
1941 parse_num_param_(request, ESPHOME_F("target_temperature"), base_call,
1943 parse_num_param_(request, ESPHOME_F("target_temperature_low"), base_call,
1945 parse_num_param_(request, ESPHOME_F("target_temperature_high"), base_call,
1947
1948 // Parse away mode parameter
1949 parse_bool_param_(request, ESPHOME_F("away"), base_call, &water_heater::WaterHeaterCall::set_away);
1950
1951 // Parse on/off parameter
1952 parse_bool_param_(request, ESPHOME_F("is_on"), base_call, &water_heater::WaterHeaterCall::set_on);
1953
1954 DEFER_ACTION(call, call.perform());
1955 request->send(200);
1956 return;
1957 }
1958 request->send(404);
1959}
1960
1962 return web_server->water_heater_json_(static_cast<water_heater::WaterHeater *>(source), DETAIL_STATE);
1963}
1965 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
1966 return web_server->water_heater_json_(static_cast<water_heater::WaterHeater *>(source), DETAIL_ALL);
1967}
1968json::SerializationBuffer<> WebServer::water_heater_json_(water_heater::WaterHeater *obj, JsonDetail start_config) {
1969 json::JsonBuilder builder;
1970 JsonObject root = builder.root();
1971
1972 const auto mode = obj->get_mode();
1974
1975 set_json_icon_state_value(root, obj, "water_heater", mode_s, mode, start_config);
1976
1977 auto traits = obj->get_traits();
1978
1979 if (start_config == DETAIL_ALL) {
1980 JsonArray modes = root[ESPHOME_F("modes")].to<JsonArray>();
1981 for (auto m : traits.get_supported_modes())
1982 modes.add(json_state_str(water_heater::water_heater_mode_to_string(m)));
1983 root[ESPHOME_F("min_temp")] = traits.get_min_temperature();
1984 root[ESPHOME_F("max_temp")] = traits.get_max_temperature();
1985 root[ESPHOME_F("step")] = traits.get_target_temperature_step();
1986 this->add_sorting_info_(root, obj);
1987 }
1988
1989 if (traits.get_supports_current_temperature()) {
1990 float current = obj->get_current_temperature();
1991 if (!std::isnan(current))
1992 root[ESPHOME_F("current_temperature")] = current;
1993 }
1994
1995 if (traits.get_supports_two_point_target_temperature()) {
1996 float low = obj->get_target_temperature_low();
1997 float high = obj->get_target_temperature_high();
1998 if (!std::isnan(low))
1999 root[ESPHOME_F("target_temperature_low")] = low;
2000 if (!std::isnan(high))
2001 root[ESPHOME_F("target_temperature_high")] = high;
2002 } else {
2003 float target = obj->get_target_temperature();
2004 if (!std::isnan(target))
2005 root[ESPHOME_F("target_temperature")] = target;
2006 }
2007
2008 if (traits.get_supports_away_mode()) {
2009 root[ESPHOME_F("away")] = obj->is_away();
2010 }
2011
2012 if (traits.has_feature_flags(water_heater::WATER_HEATER_SUPPORTS_ON_OFF)) {
2013 root[ESPHOME_F("is_on")] = obj->is_on();
2014 }
2015
2016 return builder.serialize();
2017}
2018#endif
2019
2020#ifdef USE_INFRARED
2021void WebServer::handle_infrared_request(AsyncWebServerRequest *request, const UrlMatch &match) {
2022 for (infrared::Infrared *obj : App.get_infrareds()) {
2023 auto entity_match = match.match_entity(obj);
2024 if (!entity_match.matched)
2025 continue;
2026
2027 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
2028 auto detail = get_request_detail(request);
2029 auto data = this->infrared_json_(obj, detail);
2030 request->send(200, ESPHOME_F("application/json"), data.c_str());
2031 return;
2032 }
2033 if (!match.method_equals(ESPHOME_F("transmit"))) {
2034 request->send(404);
2035 return;
2036 }
2037
2038 // Only allow transmit if the device supports it
2039 if (!obj->has_transmitter()) {
2040 request->send(400, ESPHOME_F("text/plain"), ESPHOME_F("Device does not support transmission"));
2041 return;
2042 }
2043
2044 // Parse parameters
2045 auto call = obj->make_call();
2046
2047 // Parse carrier frequency (optional)
2048 {
2049 auto value = parse_number<uint32_t>(request->arg(ESPHOME_F("carrier_frequency")).c_str());
2050 if (value.has_value()) {
2051 call.set_carrier_frequency(*value);
2052 }
2053 }
2054
2055 // Parse repeat count (optional, defaults to 1)
2056 {
2057 auto value = parse_number<uint32_t>(request->arg(ESPHOME_F("repeat_count")).c_str());
2058 if (value.has_value()) {
2059 call.set_repeat_count(*value);
2060 }
2061 }
2062
2063 // Parse base64url-encoded raw timings (required)
2064 // Base64url is URL-safe: uses A-Za-z0-9-_ (no special characters needing escaping)
2065 const auto &data_arg = request->arg(ESPHOME_F("data"));
2066
2067 // Validate base64url is not empty (also catches missing parameter since arg() returns empty string)
2068 // Arduino String has isEmpty() not empty(), use length() for cross-platform compatibility
2069 if (data_arg.length() == 0) { // NOLINT(readability-container-size-empty)
2070 request->send(400, ESPHOME_F("text/plain"), ESPHOME_F("Missing or empty 'data' parameter"));
2071 return;
2072 }
2073
2074 // Defer to main loop for thread safety. Move encoded string into lambda to ensure
2075 // it outlives the call - set_raw_timings_base64url stores a pointer, so the string
2076 // must remain valid until perform() completes.
2077 // ESP8266 also needs this because ESPAsyncWebServer callbacks run in "sys" context.
2078 this->defer([call, encoded = std::string(data_arg.c_str(), data_arg.length())]() mutable {
2079 call.set_raw_timings_base64url(encoded);
2080 call.perform();
2081 });
2082
2083 request->send(200);
2084 return;
2085 }
2086 request->send(404);
2087}
2088
2090 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
2091 return web_server->infrared_json_(static_cast<infrared::Infrared *>(source), DETAIL_ALL);
2092}
2093
2094json::SerializationBuffer<> WebServer::infrared_json_(infrared::Infrared *obj, JsonDetail start_config) {
2095 json::JsonBuilder builder;
2096 JsonObject root = builder.root();
2097
2098 set_json_icon_state_value(root, obj, "infrared", "", 0, start_config);
2099
2100 auto traits = obj->get_traits();
2101
2102 root[ESPHOME_F("supports_transmitter")] = traits.get_supports_transmitter();
2103 root[ESPHOME_F("supports_receiver")] = traits.get_supports_receiver();
2104
2105 if (start_config == DETAIL_ALL) {
2106 this->add_sorting_info_(root, obj);
2107 }
2108
2109 return builder.serialize();
2110}
2111#endif
2112
2113#ifdef USE_RADIO_FREQUENCY
2114void WebServer::handle_radio_frequency_request(AsyncWebServerRequest *request, const UrlMatch &match) {
2115 for (radio_frequency::RadioFrequency *obj : App.get_radio_frequencies()) {
2116 auto entity_match = match.match_entity(obj);
2117 if (!entity_match.matched)
2118 continue;
2119
2120 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
2121 auto detail = get_request_detail(request);
2122 auto data = this->radio_frequency_json_(obj, detail);
2123 request->send(200, ESPHOME_F("application/json"), data.c_str());
2124 return;
2125 }
2126 if (!match.method_equals(ESPHOME_F("transmit"))) {
2127 request->send(404);
2128 return;
2129 }
2130
2131 // Only allow transmit if the device supports it
2133 request->send(400, ESPHOME_F("text/plain"), ESPHOME_F("Device does not support transmission"));
2134 return;
2135 }
2136
2137 auto call = obj->make_call();
2138
2139 // Parse carrier frequency (optional — overrides IC default)
2140 {
2141 auto value = parse_number<uint32_t>(request->arg(ESPHOME_F("frequency")).c_str());
2142 if (value.has_value()) {
2143 call.set_frequency(*value);
2144 }
2145 }
2146
2147 // Parse repeat count (optional, defaults to 1)
2148 {
2149 auto value = parse_number<uint32_t>(request->arg(ESPHOME_F("repeat_count")).c_str());
2150 if (value.has_value()) {
2151 call.set_repeat_count(*value);
2152 }
2153 }
2154
2155 // Parse base64url-encoded raw timings (required)
2156 // Base64url is URL-safe: uses A-Za-z0-9-_ (no special characters needing escaping)
2157 const auto &data_arg = request->arg(ESPHOME_F("data"));
2158
2159 // Validate base64url is not empty (also catches missing parameter since arg() returns empty string)
2160 // Arduino String has isEmpty() not empty(), use length() for cross-platform compatibility
2161 if (data_arg.length() == 0) { // NOLINT(readability-container-size-empty)
2162 request->send(400, ESPHOME_F("text/plain"), ESPHOME_F("Missing or empty 'data' parameter"));
2163 return;
2164 }
2165
2166 // Defer to main loop for thread safety. Move encoded string into lambda to ensure
2167 // it outlives the call - set_raw_timings_base64url stores a pointer, so the string
2168 // must remain valid until perform() completes.
2169 // ESP8266 also needs this because ESPAsyncWebServer callbacks run in "sys" context.
2170 this->defer([call, encoded = std::string(data_arg.c_str(), data_arg.length())]() mutable {
2171 call.set_raw_timings_base64url(encoded);
2172 call.perform();
2173 });
2174
2175 request->send(200);
2176 return;
2177 }
2178 request->send(404);
2179}
2180
2182 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
2183 return web_server->radio_frequency_json_(static_cast<radio_frequency::RadioFrequency *>(source), DETAIL_ALL);
2184}
2185
2186json::SerializationBuffer<> WebServer::radio_frequency_json_(radio_frequency::RadioFrequency *obj,
2187 JsonDetail start_config) {
2188 json::JsonBuilder builder;
2189 JsonObject root = builder.root();
2190
2191 set_json_icon_state_value(root, obj, "radio_frequency", "", 0, start_config);
2192
2193 const auto &traits = obj->get_traits();
2194 auto caps = obj->get_capability_flags();
2195
2196 root[ESPHOME_F("supports_transmitter")] = bool(caps & radio_frequency::CAPABILITY_TRANSMITTER);
2197 root[ESPHOME_F("supports_receiver")] = bool(caps & radio_frequency::CAPABILITY_RECEIVER);
2198 if (traits.get_frequency_min_hz() != 0) {
2199 root[ESPHOME_F("frequency_min")] = traits.get_frequency_min_hz();
2200 root[ESPHOME_F("frequency_max")] = traits.get_frequency_max_hz();
2201 }
2202
2203 if (start_config == DETAIL_ALL) {
2204 this->add_sorting_info_(root, obj);
2205 }
2206
2207 return builder.serialize();
2208}
2209#endif
2210
2211#ifdef USE_EVENT
2213 if (!this->include_internal_ && obj->is_internal())
2214 return;
2215 this->events_.deferrable_send_state(obj, "state", event_state_json_generator);
2216}
2217
2218void WebServer::handle_event_request(AsyncWebServerRequest *request, const UrlMatch &match) {
2219 for (event::Event *obj : App.get_events()) {
2220 auto entity_match = match.match_entity(obj);
2221 if (!entity_match.matched)
2222 continue;
2223
2224 // Note: request->method() is always HTTP_GET here (canHandle ensures this)
2225 if (entity_match.action_is_empty) {
2226 auto detail = get_request_detail(request);
2227 auto data = this->event_json_(obj, StringRef(), detail);
2228 request->send(200, "application/json", data.c_str());
2229 return;
2230 }
2231 }
2232 request->send(404);
2233}
2234
2235static StringRef get_event_type(event::Event *event) { return event ? event->get_last_event_type() : StringRef(); }
2236
2238 auto *event = static_cast<event::Event *>(source);
2239 return web_server->event_json_(event, get_event_type(event), DETAIL_STATE);
2240}
2241// NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
2243 auto *event = static_cast<event::Event *>(source);
2244 return web_server->event_json_(event, get_event_type(event), DETAIL_ALL);
2245}
2246json::SerializationBuffer<> WebServer::event_json_(event::Event *obj, StringRef event_type, JsonDetail start_config) {
2247 json::JsonBuilder builder;
2248 JsonObject root = builder.root();
2249
2250 set_json_id(root, obj, "event", start_config);
2251 if (!event_type.empty()) {
2252 root[ESPHOME_F("event_type")] = event_type;
2253 }
2254 if (start_config == DETAIL_ALL) {
2255 JsonArray event_types = root[ESPHOME_F("event_types")].to<JsonArray>();
2256 for (const char *event_type : obj->get_event_types()) {
2257 event_types.add(event_type);
2258 }
2259 char dc_buf[MAX_DEVICE_CLASS_LENGTH];
2260 root[ESPHOME_F("device_class")] = obj->get_device_class_to(dc_buf);
2261 this->add_sorting_info_(root, obj);
2262 }
2263
2264 return builder.serialize();
2265}
2266// NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
2267#endif
2268
2269#ifdef USE_UPDATE
2271 this->events_.deferrable_send_state(obj, "state", update_state_json_generator);
2272}
2273void WebServer::handle_update_request(AsyncWebServerRequest *request, const UrlMatch &match) {
2274 for (update::UpdateEntity *obj : App.get_updates()) {
2275 auto entity_match = match.match_entity(obj);
2276 if (!entity_match.matched)
2277 continue;
2278
2279 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
2280 auto detail = get_request_detail(request);
2281 auto data = this->update_json_(obj, detail);
2282 request->send(200, "application/json", data.c_str());
2283 return;
2284 }
2285
2286 if (!match.method_equals(ESPHOME_F("install"))) {
2287 request->send(404);
2288 return;
2289 }
2290
2291 DEFER_ACTION(obj, obj->perform());
2292 request->send(200);
2293 return;
2294 }
2295 request->send(404);
2296}
2298 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
2299 return web_server->update_json_((update::UpdateEntity *) (source), DETAIL_STATE);
2300}
2302 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
2303 return web_server->update_json_((update::UpdateEntity *) (source), DETAIL_ALL);
2304}
2305json::SerializationBuffer<> WebServer::update_json_(update::UpdateEntity *obj, JsonDetail start_config) {
2306 // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
2307 json::JsonBuilder builder;
2308 JsonObject root = builder.root();
2309
2310 set_json_icon_state_value(root, obj, "update", json_state_str(update::update_state_to_string(obj->state)),
2311 obj->update_info.latest_version, start_config);
2312 if (start_config == DETAIL_ALL) {
2313 root[ESPHOME_F("current_version")] = obj->update_info.current_version;
2314 root[ESPHOME_F("title")] = obj->update_info.title;
2315 // Truncate long changelogs — full text available via release_url
2316 constexpr size_t max_summary_len = 256;
2317 root[ESPHOME_F("summary")] = obj->update_info.summary.size() <= max_summary_len
2318 ? obj->update_info.summary
2319 : obj->update_info.summary.substr(0, max_summary_len);
2320 root[ESPHOME_F("release_url")] = obj->update_info.release_url;
2321 this->add_sorting_info_(root, obj);
2322 }
2323
2324 return builder.serialize();
2325 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
2326}
2327#endif
2328
2329bool WebServer::canHandle(AsyncWebServerRequest *request) const {
2330#ifdef USE_ESP32
2331 char url_buf[AsyncWebServerRequest::URL_BUF_SIZE];
2332 StringRef url = request->url_to(url_buf);
2333#else
2334 const auto &url = request->url();
2335#endif
2336 const auto method = request->method();
2337
2338 // Static URL checks - use ESPHOME_F to keep strings in flash on ESP8266
2339 if (url == ESPHOME_F("/"))
2340 return true;
2341#if !defined(USE_ESP32) && defined(USE_ARDUINO)
2342 if (url == ESPHOME_F("/events"))
2343 return true;
2344#endif
2345#ifdef USE_WEBSERVER_CSS_INCLUDE
2346 if (url == ESPHOME_F("/0.css"))
2347 return true;
2348#endif
2349#ifdef USE_WEBSERVER_JS_INCLUDE
2350 if (url == ESPHOME_F("/0.js"))
2351 return true;
2352#endif
2353
2354#ifdef USE_WEBSERVER_PRIVATE_NETWORK_ACCESS
2355 if (method == HTTP_OPTIONS && request->hasHeader(ESPHOME_F("Access-Control-Request-Private-Network")))
2356 return true;
2357#endif
2358
2359 // Parse URL for component checks
2360 UrlMatch match = match_url(url.c_str(), url.length(), true);
2361 if (!match.valid)
2362 return false;
2363
2364 // Common pattern check
2365 bool is_get = method == HTTP_GET;
2366 bool is_post = method == HTTP_POST;
2367 bool is_get_or_post = is_get || is_post;
2368
2369 if (!is_get_or_post)
2370 return false;
2371
2372 // Check GET-only domains - use ESPHOME_F to keep strings in flash on ESP8266
2373 if (is_get) {
2374#ifdef USE_SENSOR
2375 if (match.domain_equals(ESPHOME_F("sensor")))
2376 return true;
2377#endif
2378#ifdef USE_BINARY_SENSOR
2379 if (match.domain_equals(ESPHOME_F("binary_sensor")))
2380 return true;
2381#endif
2382#ifdef USE_TEXT_SENSOR
2383 if (match.domain_equals(ESPHOME_F("text_sensor")))
2384 return true;
2385#endif
2386#ifdef USE_EVENT
2387 if (match.domain_equals(ESPHOME_F("event")))
2388 return true;
2389#endif
2390 }
2391
2392 // Check GET+POST domains
2393 if (is_get_or_post) {
2394#ifdef USE_SWITCH
2395 if (match.domain_equals(ESPHOME_F("switch")))
2396 return true;
2397#endif
2398#ifdef USE_BUTTON
2399 if (match.domain_equals(ESPHOME_F("button")))
2400 return true;
2401#endif
2402#ifdef USE_FAN
2403 if (match.domain_equals(ESPHOME_F("fan")))
2404 return true;
2405#endif
2406#ifdef USE_LIGHT
2407 if (match.domain_equals(ESPHOME_F("light")))
2408 return true;
2409#endif
2410#ifdef USE_COVER
2411 if (match.domain_equals(ESPHOME_F("cover")))
2412 return true;
2413#endif
2414#ifdef USE_NUMBER
2415 if (match.domain_equals(ESPHOME_F("number")))
2416 return true;
2417#endif
2418#ifdef USE_DATETIME_DATE
2419 if (match.domain_equals(ESPHOME_F("date")))
2420 return true;
2421#endif
2422#ifdef USE_DATETIME_TIME
2423 if (match.domain_equals(ESPHOME_F("time")))
2424 return true;
2425#endif
2426#ifdef USE_DATETIME_DATETIME
2427 if (match.domain_equals(ESPHOME_F("datetime")))
2428 return true;
2429#endif
2430#ifdef USE_TEXT
2431 if (match.domain_equals(ESPHOME_F("text")))
2432 return true;
2433#endif
2434#ifdef USE_SELECT
2435 if (match.domain_equals(ESPHOME_F("select")))
2436 return true;
2437#endif
2438#ifdef USE_CLIMATE
2439 if (match.domain_equals(ESPHOME_F("climate")))
2440 return true;
2441#endif
2442#ifdef USE_LOCK
2443 if (match.domain_equals(ESPHOME_F("lock")))
2444 return true;
2445#endif
2446#ifdef USE_VALVE
2447 if (match.domain_equals(ESPHOME_F("valve")))
2448 return true;
2449#endif
2450#ifdef USE_ALARM_CONTROL_PANEL
2451 if (match.domain_equals(ESPHOME_F("alarm_control_panel")))
2452 return true;
2453#endif
2454#ifdef USE_UPDATE
2455 if (match.domain_equals(ESPHOME_F("update")))
2456 return true;
2457#endif
2458#ifdef USE_WATER_HEATER
2459 if (match.domain_equals(ESPHOME_F("water_heater")))
2460 return true;
2461#endif
2462#ifdef USE_INFRARED
2463 if (match.domain_equals(ESPHOME_F("infrared")))
2464 return true;
2465#endif
2466#ifdef USE_RADIO_FREQUENCY
2467 if (match.domain_equals(ESPHOME_F("radio_frequency")))
2468 return true;
2469#endif
2470 }
2471
2472 return false;
2473}
2474void WebServer::handleRequest(AsyncWebServerRequest *request) {
2475#ifdef USE_ESP32
2476 char url_buf[AsyncWebServerRequest::URL_BUF_SIZE];
2477 StringRef url = request->url_to(url_buf);
2478#else
2479 const auto &url = request->url();
2480#endif
2481
2482 // Handle static routes first
2483 if (url == ESPHOME_F("/")) {
2484 this->handle_index_request(request);
2485 return;
2486 }
2487
2488#ifdef USE_WEBSERVER_PRIVATE_NETWORK_ACCESS
2489 // Private Network Access preflight carries a cross-origin Origin by design; its handler does the
2490 // origin check itself, so let it run before the general enforcement below.
2491 if (request->method() == HTTP_OPTIONS && request->hasHeader(ESPHOME_F("Access-Control-Request-Private-Network"))) {
2492 this->handle_pna_cors_request(request);
2493 return;
2494 }
2495#endif
2496
2497 // Reject cross-origin browser requests unless the origin is explicitly allowed.
2498 if (!this->is_request_origin_allowed_(request, get_request_header(request, "Origin"))) {
2499 request->send(403);
2500 return;
2501 }
2502
2503#if !defined(USE_ESP32) && defined(USE_ARDUINO)
2504 if (url == ESPHOME_F("/events")) {
2505 this->events_.add_new_client(this, request);
2506 return;
2507 }
2508#endif
2509
2510#ifdef USE_WEBSERVER_CSS_INCLUDE
2511 if (url == ESPHOME_F("/0.css")) {
2512 this->handle_css_request(request);
2513 return;
2514 }
2515#endif
2516
2517#ifdef USE_WEBSERVER_JS_INCLUDE
2518 if (url == ESPHOME_F("/0.js")) {
2519 this->handle_js_request(request);
2520 return;
2521 }
2522#endif
2523
2524 // Parse URL for component routing
2525 // Pass HTTP method to disambiguate 3-segment URLs (GET=sub-device state, POST=main device action)
2526 UrlMatch match = match_url(url.c_str(), url.length(), false, request->method() == HTTP_POST);
2527
2528 // Route to appropriate handler based on domain
2529 // NOLINTNEXTLINE(readability-simplify-boolean-expr)
2530 if (false) { // Start chain for else-if macro pattern
2531 }
2532#ifdef USE_SENSOR
2533 else if (match.domain_equals(ESPHOME_F("sensor"))) {
2534 this->handle_sensor_request(request, match);
2535 }
2536#endif
2537#ifdef USE_SWITCH
2538 else if (match.domain_equals(ESPHOME_F("switch"))) {
2539 this->handle_switch_request(request, match);
2540 }
2541#endif
2542#ifdef USE_BUTTON
2543 else if (match.domain_equals(ESPHOME_F("button"))) {
2544 this->handle_button_request(request, match);
2545 }
2546#endif
2547#ifdef USE_BINARY_SENSOR
2548 else if (match.domain_equals(ESPHOME_F("binary_sensor"))) {
2549 this->handle_binary_sensor_request(request, match);
2550 }
2551#endif
2552#ifdef USE_FAN
2553 else if (match.domain_equals(ESPHOME_F("fan"))) {
2554 this->handle_fan_request(request, match);
2555 }
2556#endif
2557#ifdef USE_LIGHT
2558 else if (match.domain_equals(ESPHOME_F("light"))) {
2559 this->handle_light_request(request, match);
2560 }
2561#endif
2562#ifdef USE_TEXT_SENSOR
2563 else if (match.domain_equals(ESPHOME_F("text_sensor"))) {
2564 this->handle_text_sensor_request(request, match);
2565 }
2566#endif
2567#ifdef USE_COVER
2568 else if (match.domain_equals(ESPHOME_F("cover"))) {
2569 this->handle_cover_request(request, match);
2570 }
2571#endif
2572#ifdef USE_NUMBER
2573 else if (match.domain_equals(ESPHOME_F("number"))) {
2574 this->handle_number_request(request, match);
2575 }
2576#endif
2577#ifdef USE_DATETIME_DATE
2578 else if (match.domain_equals(ESPHOME_F("date"))) {
2579 this->handle_date_request(request, match);
2580 }
2581#endif
2582#ifdef USE_DATETIME_TIME
2583 else if (match.domain_equals(ESPHOME_F("time"))) {
2584 this->handle_time_request(request, match);
2585 }
2586#endif
2587#ifdef USE_DATETIME_DATETIME
2588 else if (match.domain_equals(ESPHOME_F("datetime"))) {
2589 this->handle_datetime_request(request, match);
2590 }
2591#endif
2592#ifdef USE_TEXT
2593 else if (match.domain_equals(ESPHOME_F("text"))) {
2594 this->handle_text_request(request, match);
2595 }
2596#endif
2597#ifdef USE_SELECT
2598 else if (match.domain_equals(ESPHOME_F("select"))) {
2599 this->handle_select_request(request, match);
2600 }
2601#endif
2602#ifdef USE_CLIMATE
2603 else if (match.domain_equals(ESPHOME_F("climate"))) {
2604 this->handle_climate_request(request, match);
2605 }
2606#endif
2607#ifdef USE_LOCK
2608 else if (match.domain_equals(ESPHOME_F("lock"))) {
2609 this->handle_lock_request(request, match);
2610 }
2611#endif
2612#ifdef USE_VALVE
2613 else if (match.domain_equals(ESPHOME_F("valve"))) {
2614 this->handle_valve_request(request, match);
2615 }
2616#endif
2617#ifdef USE_ALARM_CONTROL_PANEL
2618 else if (match.domain_equals(ESPHOME_F("alarm_control_panel"))) {
2619 this->handle_alarm_control_panel_request(request, match);
2620 }
2621#endif
2622#ifdef USE_UPDATE
2623 else if (match.domain_equals(ESPHOME_F("update"))) {
2624 this->handle_update_request(request, match);
2625 }
2626#endif
2627#ifdef USE_WATER_HEATER
2628 else if (match.domain_equals(ESPHOME_F("water_heater"))) {
2629 this->handle_water_heater_request(request, match);
2630 }
2631#endif
2632#ifdef USE_INFRARED
2633 else if (match.domain_equals(ESPHOME_F("infrared"))) {
2634 this->handle_infrared_request(request, match);
2635 }
2636#endif
2637#ifdef USE_RADIO_FREQUENCY
2638 else if (match.domain_equals(ESPHOME_F("radio_frequency"))) {
2639 this->handle_radio_frequency_request(request, match);
2640 }
2641#endif
2642 else {
2643 // No matching handler found - send 404
2644 ESP_LOGV(TAG, "Request for unknown URL: %s", url.c_str());
2645 request->send(404, ESPHOME_F("text/plain"), ESPHOME_F("Not Found"));
2646 }
2647}
2648
2649bool WebServer::isRequestHandlerTrivial() const { return false; }
2650
2651void WebServer::add_sorting_info_(JsonObject &root, EntityBase *entity) {
2652#ifdef USE_WEBSERVER_SORTING
2653 if (this->sorting_entitys_.contains(entity)) {
2654 root[ESPHOME_F("sorting_weight")] = this->sorting_entitys_[entity].weight;
2655 if (this->sorting_groups_.contains(this->sorting_entitys_[entity].group_id)) {
2656 root[ESPHOME_F("sorting_group")] = this->sorting_groups_[this->sorting_entitys_[entity].group_id].name;
2657 }
2658 }
2659#endif
2660}
2661
2662#ifdef USE_WEBSERVER_SORTING
2663void WebServer::add_entity_config(EntityBase *entity, float weight, uint64_t group) {
2664 this->sorting_entitys_[entity] = SortingComponents{weight, group};
2665}
2666
2667void WebServer::add_sorting_group(uint64_t group_id, const std::string &group_name, float weight) {
2668 this->sorting_groups_[group_id] = SortingGroup{group_name, weight};
2669}
2670#endif
2671
2672} // namespace esphome::web_server
2673#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)
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