ESPHome 2026.8.0-dev
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[18];
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 this->add_sorting_info_(root, obj);
1119 }
1120
1121 return builder.serialize();
1122}
1123#endif
1124
1125#ifdef USE_NUMBER
1127 if (!this->include_internal_ && obj->is_internal())
1128 return;
1129 this->events_.deferrable_send_state(obj, "state", number_state_json_generator);
1130}
1131void WebServer::handle_number_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1132 for (auto *obj : App.get_numbers()) {
1133 auto entity_match = match.match_entity(obj);
1134 if (!entity_match.matched)
1135 continue;
1136
1137 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1138 auto detail = get_request_detail(request);
1139 auto data = this->number_json_(obj, obj->state, detail);
1140 request->send(200, "application/json", data.c_str());
1141 return;
1142 }
1143 if (!match.method_equals(ESPHOME_F("set"))) {
1144 request->send(404);
1145 return;
1146 }
1147
1148 auto call = obj->make_call();
1149 parse_num_param_(request, ESPHOME_F("value"), call, &decltype(call)::set_value);
1150
1151 DEFER_ACTION(call, call.perform());
1152 request->send(200);
1153 return;
1154 }
1155 request->send(404);
1156}
1157
1159 return web_server->number_json_((number::Number *) (source), ((number::Number *) (source))->state, DETAIL_STATE);
1160}
1162 return web_server->number_json_((number::Number *) (source), ((number::Number *) (source))->state, DETAIL_ALL);
1163}
1164json::SerializationBuffer<> WebServer::number_json_(number::Number *obj, float value, JsonDetail start_config) {
1165 json::JsonBuilder builder;
1166 JsonObject root = builder.root();
1167
1168 const auto uom_ref = obj->get_unit_of_measurement_ref();
1169 const int8_t accuracy = step_to_accuracy_decimals(obj->traits.get_step());
1170
1171 // Need two buffers: one for value, one for state with UOM
1172 char val_buf[VALUE_ACCURACY_MAX_LEN];
1173 char state_buf[VALUE_ACCURACY_MAX_LEN];
1174 const char *val_str = std::isnan(value) ? "\"NaN\"" : (value_accuracy_to_buf(val_buf, value, accuracy), val_buf);
1175 const char *state_str =
1176 std::isnan(value) ? "NA" : (value_accuracy_with_uom_to_buf(state_buf, value, accuracy, uom_ref), state_buf);
1177 set_json_icon_state_value(root, obj, "number", state_str, val_str, start_config);
1178 if (start_config == DETAIL_ALL) {
1179 // ArduinoJson copies the string immediately, so we can reuse val_buf
1180 root[ESPHOME_F("min_value")] = (value_accuracy_to_buf(val_buf, obj->traits.get_min_value(), accuracy), val_buf);
1181 root[ESPHOME_F("max_value")] = (value_accuracy_to_buf(val_buf, obj->traits.get_max_value(), accuracy), val_buf);
1182 root[ESPHOME_F("step")] = (value_accuracy_to_buf(val_buf, obj->traits.get_step(), accuracy), val_buf);
1183 root[ESPHOME_F("mode")] = (int) obj->traits.get_mode();
1184 if (!uom_ref.empty())
1185 root[ESPHOME_F("uom")] = uom_ref.c_str();
1186 this->add_sorting_info_(root, obj);
1187 }
1188
1189 return builder.serialize();
1190}
1191#endif
1192
1193#ifdef USE_DATETIME_DATE
1195 if (!this->include_internal_ && obj->is_internal())
1196 return;
1197 this->events_.deferrable_send_state(obj, "state", date_state_json_generator);
1198}
1199void WebServer::handle_date_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1200 for (auto *obj : App.get_dates()) {
1201 auto entity_match = match.match_entity(obj);
1202 if (!entity_match.matched)
1203 continue;
1204 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1205 auto detail = get_request_detail(request);
1206 auto data = this->date_json_(obj, detail);
1207 request->send(200, "application/json", data.c_str());
1208 return;
1209 }
1210 if (!match.method_equals(ESPHOME_F("set"))) {
1211 request->send(404);
1212 return;
1213 }
1214
1215 auto call = obj->make_call();
1216
1217 const auto &value = request->arg(ESPHOME_F("value"));
1218 // Arduino String has isEmpty() not empty(), use length() for cross-platform compatibility
1219 if (value.length() == 0) { // NOLINT(readability-container-size-empty)
1220 request->send(409);
1221 return;
1222 }
1223 call.set_date(value.c_str(), value.length());
1224
1225 DEFER_ACTION(call, call.perform());
1226 request->send(200);
1227 return;
1228 }
1229 request->send(404);
1230}
1231
1233 return web_server->date_json_((datetime::DateEntity *) (source), DETAIL_STATE);
1234}
1236 return web_server->date_json_((datetime::DateEntity *) (source), DETAIL_ALL);
1237}
1238json::SerializationBuffer<> WebServer::date_json_(datetime::DateEntity *obj, JsonDetail start_config) {
1239 json::JsonBuilder builder;
1240 JsonObject root = builder.root();
1241
1242 // Format: YYYY-MM-DD (max 10 chars + null)
1243 char value[12];
1244 buf_append_printf(value, sizeof(value), 0, "%d-%02d-%02d", obj->year, obj->month, obj->day);
1245 set_json_icon_state_value(root, obj, "date", value, value, start_config);
1246 if (start_config == DETAIL_ALL) {
1247 this->add_sorting_info_(root, obj);
1248 }
1249
1250 return builder.serialize();
1251}
1252#endif // USE_DATETIME_DATE
1253
1254#ifdef USE_DATETIME_TIME
1256 if (!this->include_internal_ && obj->is_internal())
1257 return;
1258 this->events_.deferrable_send_state(obj, "state", time_state_json_generator);
1259}
1260void WebServer::handle_time_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1261 for (auto *obj : App.get_times()) {
1262 auto entity_match = match.match_entity(obj);
1263 if (!entity_match.matched)
1264 continue;
1265 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1266 auto detail = get_request_detail(request);
1267 auto data = this->time_json_(obj, detail);
1268 request->send(200, "application/json", data.c_str());
1269 return;
1270 }
1271 if (!match.method_equals(ESPHOME_F("set"))) {
1272 request->send(404);
1273 return;
1274 }
1275
1276 auto call = obj->make_call();
1277
1278 const auto &value = request->arg(ESPHOME_F("value"));
1279 // Arduino String has isEmpty() not empty(), use length() for cross-platform compatibility
1280 if (value.length() == 0) { // NOLINT(readability-container-size-empty)
1281 request->send(409);
1282 return;
1283 }
1284 call.set_time(value.c_str(), value.length());
1285
1286 DEFER_ACTION(call, call.perform());
1287 request->send(200);
1288 return;
1289 }
1290 request->send(404);
1291}
1293 return web_server->time_json_((datetime::TimeEntity *) (source), DETAIL_STATE);
1294}
1296 return web_server->time_json_((datetime::TimeEntity *) (source), DETAIL_ALL);
1297}
1298json::SerializationBuffer<> WebServer::time_json_(datetime::TimeEntity *obj, JsonDetail start_config) {
1299 json::JsonBuilder builder;
1300 JsonObject root = builder.root();
1301
1302 // Format: HH:MM:SS (8 chars + null)
1303 char value[12];
1304 buf_append_printf(value, sizeof(value), 0, "%02d:%02d:%02d", obj->hour, obj->minute, obj->second);
1305 set_json_icon_state_value(root, obj, "time", value, value, start_config);
1306 if (start_config == DETAIL_ALL) {
1307 this->add_sorting_info_(root, obj);
1308 }
1309
1310 return builder.serialize();
1311}
1312#endif // USE_DATETIME_TIME
1313
1314#ifdef USE_DATETIME_DATETIME
1316 if (!this->include_internal_ && obj->is_internal())
1317 return;
1318 this->events_.deferrable_send_state(obj, "state", datetime_state_json_generator);
1319}
1320void WebServer::handle_datetime_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1321 for (auto *obj : App.get_datetimes()) {
1322 auto entity_match = match.match_entity(obj);
1323 if (!entity_match.matched)
1324 continue;
1325 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1326 auto detail = get_request_detail(request);
1327 auto data = this->datetime_json_(obj, detail);
1328 request->send(200, "application/json", data.c_str());
1329 return;
1330 }
1331 if (!match.method_equals(ESPHOME_F("set"))) {
1332 request->send(404);
1333 return;
1334 }
1335
1336 auto call = obj->make_call();
1337
1338 const auto &value = request->arg(ESPHOME_F("value"));
1339 // Arduino String has isEmpty() not empty(), use length() for cross-platform compatibility
1340 if (value.length() == 0) { // NOLINT(readability-container-size-empty)
1341 request->send(409);
1342 return;
1343 }
1344 call.set_datetime(value.c_str(), value.length());
1345
1346 DEFER_ACTION(call, call.perform());
1347 request->send(200);
1348 return;
1349 }
1350 request->send(404);
1351}
1353 return web_server->datetime_json_((datetime::DateTimeEntity *) (source), DETAIL_STATE);
1354}
1356 return web_server->datetime_json_((datetime::DateTimeEntity *) (source), DETAIL_ALL);
1357}
1358json::SerializationBuffer<> WebServer::datetime_json_(datetime::DateTimeEntity *obj, JsonDetail start_config) {
1359 json::JsonBuilder builder;
1360 JsonObject root = builder.root();
1361
1362 // Format: YYYY-MM-DD HH:MM:SS (max 19 chars + null)
1363 char value[24];
1364 buf_append_printf(value, sizeof(value), 0, "%d-%02d-%02d %02d:%02d:%02d", obj->year, obj->month, obj->day, obj->hour,
1365 obj->minute, obj->second);
1366 set_json_icon_state_value(root, obj, "datetime", value, value, start_config);
1367 if (start_config == DETAIL_ALL) {
1368 this->add_sorting_info_(root, obj);
1369 }
1370
1371 return builder.serialize();
1372}
1373#endif // USE_DATETIME_DATETIME
1374
1375#ifdef USE_TEXT
1377 if (!this->include_internal_ && obj->is_internal())
1378 return;
1379 this->events_.deferrable_send_state(obj, "state", text_state_json_generator);
1380}
1381void WebServer::handle_text_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1382 for (auto *obj : App.get_texts()) {
1383 auto entity_match = match.match_entity(obj);
1384 if (!entity_match.matched)
1385 continue;
1386
1387 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1388 auto detail = get_request_detail(request);
1389 auto data = this->text_json_(obj, obj->state, detail);
1390 request->send(200, "application/json", data.c_str());
1391 return;
1392 }
1393 if (!match.method_equals(ESPHOME_F("set"))) {
1394 request->send(404);
1395 return;
1396 }
1397
1398 auto call = obj->make_call();
1400 request, ESPHOME_F("value"), call,
1401 static_cast<text::TextCall &(text::TextCall::*) (const char *, size_t)>(&decltype(call)::set_value));
1402
1403 DEFER_ACTION(call, call.perform());
1404 request->send(200);
1405 return;
1406 }
1407 request->send(404);
1408}
1409
1411 return web_server->text_json_((text::Text *) (source), ((text::Text *) (source))->state, DETAIL_STATE);
1412}
1414 return web_server->text_json_((text::Text *) (source), ((text::Text *) (source))->state, DETAIL_ALL);
1415}
1416json::SerializationBuffer<> WebServer::text_json_(text::Text *obj, const std::string &value, JsonDetail start_config) {
1417 json::JsonBuilder builder;
1418 JsonObject root = builder.root();
1419
1420 const char *state = obj->traits.get_mode() == text::TextMode::TEXT_MODE_PASSWORD ? "********" : value.c_str();
1421 set_json_icon_state_value(root, obj, "text", state, value.c_str(), start_config);
1422 root[ESPHOME_F("min_length")] = obj->traits.get_min_length();
1423 root[ESPHOME_F("max_length")] = obj->traits.get_max_length();
1424 root[ESPHOME_F("pattern")] = obj->traits.get_pattern_c_str();
1425 if (start_config == DETAIL_ALL) {
1426 root[ESPHOME_F("mode")] = (int) obj->traits.get_mode();
1427 this->add_sorting_info_(root, obj);
1428 }
1429
1430 return builder.serialize();
1431}
1432#endif
1433
1434#ifdef USE_SELECT
1436 if (!this->include_internal_ && obj->is_internal())
1437 return;
1438 this->events_.deferrable_send_state(obj, "state", select_state_json_generator);
1439}
1440void WebServer::handle_select_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1441 for (auto *obj : App.get_selects()) {
1442 auto entity_match = match.match_entity(obj);
1443 if (!entity_match.matched)
1444 continue;
1445
1446 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1447 auto detail = get_request_detail(request);
1448 auto data = this->select_json_(obj, obj->has_state() ? obj->current_option() : StringRef(), detail);
1449 request->send(200, "application/json", data.c_str());
1450 return;
1451 }
1452
1453 if (!match.method_equals(ESPHOME_F("set"))) {
1454 request->send(404);
1455 return;
1456 }
1457
1458 auto call = obj->make_call();
1460 request, ESPHOME_F("option"), call,
1461 static_cast<select::SelectCall &(select::SelectCall::*) (const char *, size_t)>(&decltype(call)::set_option));
1462
1463 DEFER_ACTION(call, call.perform());
1464 request->send(200);
1465 return;
1466 }
1467 request->send(404);
1468}
1470 auto *obj = (select::Select *) (source);
1471 return web_server->select_json_(obj, obj->has_state() ? obj->current_option() : StringRef(), DETAIL_STATE);
1472}
1474 auto *obj = (select::Select *) (source);
1475 return web_server->select_json_(obj, obj->has_state() ? obj->current_option() : StringRef(), DETAIL_ALL);
1476}
1477json::SerializationBuffer<> WebServer::select_json_(select::Select *obj, StringRef value, JsonDetail start_config) {
1478 json::JsonBuilder builder;
1479 JsonObject root = builder.root();
1480
1481 // value points to null-terminated string literals from codegen (via current_option())
1482 set_json_icon_state_value(root, obj, "select", value.c_str(), value.c_str(), start_config);
1483 if (start_config == DETAIL_ALL) {
1484 JsonArray opt = root[ESPHOME_F("option")].to<JsonArray>();
1485 for (auto &option : obj->traits.get_options()) {
1486 opt.add(option);
1487 }
1488 this->add_sorting_info_(root, obj);
1489 }
1490
1491 return builder.serialize();
1492}
1493#endif
1494
1495#ifdef USE_CLIMATE
1497 if (!this->include_internal_ && obj->is_internal())
1498 return;
1499 this->events_.deferrable_send_state(obj, "state", climate_state_json_generator);
1500}
1501void WebServer::handle_climate_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1502 for (auto *obj : App.get_climates()) {
1503 auto entity_match = match.match_entity(obj);
1504 if (!entity_match.matched)
1505 continue;
1506
1507 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1508 auto detail = get_request_detail(request);
1509 auto data = this->climate_json_(obj, detail);
1510 request->send(200, "application/json", data.c_str());
1511 return;
1512 }
1513
1514 if (!match.method_equals(ESPHOME_F("set"))) {
1515 request->send(404);
1516 return;
1517 }
1518
1519 auto call = obj->make_call();
1520
1521 // Parse string mode parameters
1523 request, ESPHOME_F("mode"), call,
1524 static_cast<climate::ClimateCall &(climate::ClimateCall::*) (const char *, size_t)>(&decltype(call)::set_mode));
1525 parse_cstr_param_(request, ESPHOME_F("fan_mode"), call,
1526 static_cast<climate::ClimateCall &(climate::ClimateCall::*) (const char *, size_t)>(
1527 &decltype(call)::set_fan_mode));
1528 parse_cstr_param_(request, ESPHOME_F("swing_mode"), call,
1529 static_cast<climate::ClimateCall &(climate::ClimateCall::*) (const char *, size_t)>(
1530 &decltype(call)::set_swing_mode));
1531 parse_cstr_param_(request, ESPHOME_F("preset"), call,
1532 static_cast<climate::ClimateCall &(climate::ClimateCall::*) (const char *, size_t)>(
1533 &decltype(call)::set_preset));
1534
1535 // Parse temperature parameters
1536 // static_cast needed to disambiguate overloaded setters (float vs optional<float>)
1537 using ClimateCall = decltype(call);
1538 parse_num_param_(request, ESPHOME_F("target_temperature_high"), call,
1539 static_cast<ClimateCall &(ClimateCall::*) (float)>(&ClimateCall::set_target_temperature_high));
1540 parse_num_param_(request, ESPHOME_F("target_temperature_low"), call,
1541 static_cast<ClimateCall &(ClimateCall::*) (float)>(&ClimateCall::set_target_temperature_low));
1542 parse_num_param_(request, ESPHOME_F("target_temperature"), call,
1543 static_cast<ClimateCall &(ClimateCall::*) (float)>(&ClimateCall::set_target_temperature));
1544
1545 DEFER_ACTION(call, call.perform());
1546 request->send(200);
1547 return;
1548 }
1549 request->send(404);
1550}
1552 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
1553 return web_server->climate_json_((climate::Climate *) (source), DETAIL_STATE);
1554}
1556 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
1557 return web_server->climate_json_((climate::Climate *) (source), DETAIL_ALL);
1558}
1559json::SerializationBuffer<> WebServer::climate_json_(climate::Climate *obj, JsonDetail start_config) {
1560 // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
1561 json::JsonBuilder builder;
1562 JsonObject root = builder.root();
1563 set_json_id(root, obj, "climate", start_config);
1564 const auto traits = obj->get_traits();
1565 int8_t target_accuracy = traits.get_target_temperature_accuracy_decimals();
1566 int8_t current_accuracy = traits.get_current_temperature_accuracy_decimals();
1567 char temp_buf[VALUE_ACCURACY_MAX_LEN];
1568
1569 if (start_config == DETAIL_ALL) {
1570 JsonArray opt = root[ESPHOME_F("modes")].to<JsonArray>();
1571 for (climate::ClimateMode m : traits.get_supported_modes())
1572 opt.add(json_state_str(climate::climate_mode_to_string(m)));
1573 if (traits.get_supports_fan_modes()) {
1574 JsonArray opt = root[ESPHOME_F("fan_modes")].to<JsonArray>();
1575 for (climate::ClimateFanMode m : traits.get_supported_fan_modes())
1576 opt.add(json_state_str(climate::climate_fan_mode_to_string(m)));
1577 }
1578
1579 if (!traits.get_supported_custom_fan_modes().empty()) {
1580 JsonArray opt = root[ESPHOME_F("custom_fan_modes")].to<JsonArray>();
1581 for (auto const &custom_fan_mode : traits.get_supported_custom_fan_modes())
1582 opt.add(custom_fan_mode);
1583 }
1584 if (traits.get_supports_swing_modes()) {
1585 JsonArray opt = root[ESPHOME_F("swing_modes")].to<JsonArray>();
1586 for (auto swing_mode : traits.get_supported_swing_modes())
1587 opt.add(json_state_str(climate::climate_swing_mode_to_string(swing_mode)));
1588 }
1589 if (traits.get_supports_presets()) {
1590 JsonArray opt = root[ESPHOME_F("presets")].to<JsonArray>();
1591 for (climate::ClimatePreset m : traits.get_supported_presets())
1592 opt.add(json_state_str(climate::climate_preset_to_string(m)));
1593 }
1594 if (!traits.get_supported_custom_presets().empty()) {
1595 JsonArray opt = root[ESPHOME_F("custom_presets")].to<JsonArray>();
1596 for (auto const &custom_preset : traits.get_supported_custom_presets())
1597 opt.add(custom_preset);
1598 }
1599 root[ESPHOME_F("max_temp")] =
1600 (value_accuracy_to_buf(temp_buf, traits.get_visual_max_temperature(), target_accuracy), temp_buf);
1601 root[ESPHOME_F("min_temp")] =
1602 (value_accuracy_to_buf(temp_buf, traits.get_visual_min_temperature(), target_accuracy), temp_buf);
1603 root[ESPHOME_F("step")] = traits.get_visual_target_temperature_step();
1604 this->add_sorting_info_(root, obj);
1605 }
1606
1607 bool has_state = false;
1608 root[ESPHOME_F("mode")] = json_state_str(climate_mode_to_string(obj->mode));
1609 if (traits.has_feature_flags(climate::CLIMATE_SUPPORTS_ACTION)) {
1610 root[ESPHOME_F("action")] = json_state_str(climate_action_to_string(obj->action));
1611 root[ESPHOME_F("state")] = root[ESPHOME_F("action")];
1612 has_state = true;
1613 }
1614 if (traits.get_supports_fan_modes() && obj->fan_mode.has_value()) {
1615 root[ESPHOME_F("fan_mode")] = json_state_str(climate_fan_mode_to_string(obj->fan_mode.value()));
1616 }
1617 if (!traits.get_supported_custom_fan_modes().empty() && obj->has_custom_fan_mode()) {
1618 root[ESPHOME_F("custom_fan_mode")] = obj->get_custom_fan_mode();
1619 }
1620 if (traits.get_supports_presets() && obj->preset.has_value()) {
1621 root[ESPHOME_F("preset")] = json_state_str(climate_preset_to_string(obj->preset.value()));
1622 }
1623 if (!traits.get_supported_custom_presets().empty() && obj->has_custom_preset()) {
1624 root[ESPHOME_F("custom_preset")] = obj->get_custom_preset();
1625 }
1626 if (traits.get_supports_swing_modes()) {
1627 root[ESPHOME_F("swing_mode")] = json_state_str(climate_swing_mode_to_string(obj->swing_mode));
1628 }
1629 if (traits.has_feature_flags(climate::CLIMATE_SUPPORTS_CURRENT_TEMPERATURE)) {
1630 root[ESPHOME_F("current_temperature")] =
1631 std::isnan(obj->current_temperature)
1632 ? "NA"
1633 : (value_accuracy_to_buf(temp_buf, obj->current_temperature, current_accuracy), temp_buf);
1634 }
1635 if (traits.has_feature_flags(climate::CLIMATE_SUPPORTS_CURRENT_HUMIDITY)) {
1636 root[ESPHOME_F("current_humidity")] = std::isnan(obj->current_humidity)
1637 ? "NA"
1638 : (value_accuracy_to_buf(temp_buf, obj->current_humidity, 0), temp_buf);
1639 }
1640 if (traits.has_feature_flags(climate::CLIMATE_SUPPORTS_TWO_POINT_TARGET_TEMPERATURE |
1642 root[ESPHOME_F("target_temperature_low")] =
1643 (value_accuracy_to_buf(temp_buf, obj->target_temperature_low, target_accuracy), temp_buf);
1644 root[ESPHOME_F("target_temperature_high")] =
1645 (value_accuracy_to_buf(temp_buf, obj->target_temperature_high, target_accuracy), temp_buf);
1646 if (!has_state) {
1647 root[ESPHOME_F("state")] =
1649 target_accuracy),
1650 temp_buf);
1651 }
1652 } else {
1653 root[ESPHOME_F("target_temperature")] =
1654 (value_accuracy_to_buf(temp_buf, obj->target_temperature, target_accuracy), temp_buf);
1655 if (!has_state)
1656 root[ESPHOME_F("state")] = root[ESPHOME_F("target_temperature")];
1657 }
1658
1659 return builder.serialize();
1660 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
1661}
1662#endif
1663
1664#ifdef USE_LOCK
1666
1667static void execute_lock_action(lock::Lock *obj, LockAction action) {
1668 switch (action) {
1669 case LOCK_ACTION_LOCK:
1670 obj->lock();
1671 break;
1672 case LOCK_ACTION_UNLOCK:
1673 obj->unlock();
1674 break;
1675 case LOCK_ACTION_OPEN:
1676 obj->open();
1677 break;
1678 default:
1679 break;
1680 }
1681}
1682
1684 if (!this->include_internal_ && obj->is_internal())
1685 return;
1686 this->events_.deferrable_send_state(obj, "state", lock_state_json_generator);
1687}
1688void WebServer::handle_lock_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1689 for (lock::Lock *obj : App.get_locks()) {
1690 auto entity_match = match.match_entity(obj);
1691 if (!entity_match.matched)
1692 continue;
1693
1694 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1695 auto detail = get_request_detail(request);
1696 auto data = this->lock_json_(obj, obj->state, detail);
1697 request->send(200, "application/json", data.c_str());
1698 return;
1699 }
1700
1702
1703 if (match.method_equals(ESPHOME_F("lock"))) {
1704 action = LOCK_ACTION_LOCK;
1705 } else if (match.method_equals(ESPHOME_F("unlock"))) {
1706 action = LOCK_ACTION_UNLOCK;
1707 } else if (match.method_equals(ESPHOME_F("open"))) {
1708 action = LOCK_ACTION_OPEN;
1709 }
1710
1711 if (action != LOCK_ACTION_NONE) {
1712 this->defer([obj, action]() { execute_lock_action(obj, action); });
1713 request->send(200);
1714 } else {
1715 request->send(404);
1716 }
1717 return;
1718 }
1719 request->send(404);
1720}
1722 return web_server->lock_json_((lock::Lock *) (source), ((lock::Lock *) (source))->state, DETAIL_STATE);
1723}
1725 return web_server->lock_json_((lock::Lock *) (source), ((lock::Lock *) (source))->state, DETAIL_ALL);
1726}
1727json::SerializationBuffer<> WebServer::lock_json_(lock::Lock *obj, lock::LockState value, JsonDetail start_config) {
1728 json::JsonBuilder builder;
1729 JsonObject root = builder.root();
1730
1731 set_json_icon_state_value(root, obj, "lock", json_state_str(lock::lock_state_to_string(value)), value, start_config);
1732 if (start_config == DETAIL_ALL) {
1733 this->add_sorting_info_(root, obj);
1734 }
1735
1736 return builder.serialize();
1737}
1738#endif
1739
1740#ifdef USE_VALVE
1742 if (!this->include_internal_ && obj->is_internal())
1743 return;
1744 this->events_.deferrable_send_state(obj, "state", valve_state_json_generator);
1745}
1746void WebServer::handle_valve_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1747 for (valve::Valve *obj : App.get_valves()) {
1748 auto entity_match = match.match_entity(obj);
1749 if (!entity_match.matched)
1750 continue;
1751
1752 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1753 auto detail = get_request_detail(request);
1754 auto data = this->valve_json_(obj, detail);
1755 request->send(200, "application/json", data.c_str());
1756 return;
1757 }
1758
1759 auto call = obj->make_call();
1760
1761 // Lookup table for valve methods
1762 static const struct {
1763 const char *name;
1764 valve::ValveCall &(valve::ValveCall::*action)();
1765 } METHODS[] = {
1770 };
1771
1772 bool found = false;
1773 for (const auto &method : METHODS) {
1774 if (match.method_equals(method.name)) {
1775 (call.*method.action)();
1776 found = true;
1777 break;
1778 }
1779 }
1780
1781 if (!found && !match.method_equals(ESPHOME_F("set"))) {
1782 request->send(404);
1783 return;
1784 }
1785
1786 auto traits = obj->get_traits();
1787 if (request->hasArg(ESPHOME_F("position")) && !traits.get_supports_position()) {
1788 request->send(409);
1789 return;
1790 }
1791
1792 parse_num_param_(request, ESPHOME_F("position"), call, &decltype(call)::set_position);
1793
1794 DEFER_ACTION(call, call.perform());
1795 request->send(200);
1796 return;
1797 }
1798 request->send(404);
1799}
1801 return web_server->valve_json_((valve::Valve *) (source), DETAIL_STATE);
1802}
1804 return web_server->valve_json_((valve::Valve *) (source), DETAIL_ALL);
1805}
1806json::SerializationBuffer<> WebServer::valve_json_(valve::Valve *obj, JsonDetail start_config) {
1807 json::JsonBuilder builder;
1808 JsonObject root = builder.root();
1809
1810 set_json_icon_state_value(root, obj, "valve", obj->is_fully_closed() ? "CLOSED" : "OPEN", obj->position,
1811 start_config);
1812 root[ESPHOME_F("current_operation")] = json_state_str(valve::valve_operation_to_str(obj->current_operation));
1813
1814 if (obj->get_traits().get_supports_position())
1815 root[ESPHOME_F("position")] = obj->position;
1816 if (start_config == DETAIL_ALL) {
1817 this->add_sorting_info_(root, obj);
1818 }
1819
1820 return builder.serialize();
1821}
1822#endif
1823
1824#ifdef USE_ALARM_CONTROL_PANEL
1826 if (!this->include_internal_ && obj->is_internal())
1827 return;
1828 this->events_.deferrable_send_state(obj, "state", alarm_control_panel_state_json_generator);
1829}
1830void WebServer::handle_alarm_control_panel_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1831 for (alarm_control_panel::AlarmControlPanel *obj : App.get_alarm_control_panels()) {
1832 auto entity_match = match.match_entity(obj);
1833 if (!entity_match.matched)
1834 continue;
1835
1836 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1837 auto detail = get_request_detail(request);
1838 auto data = this->alarm_control_panel_json_(obj, obj->get_state(), detail);
1839 request->send(200, "application/json", data.c_str());
1840 return;
1841 }
1842
1843 auto call = obj->make_call();
1845 request, ESPHOME_F("code"), call,
1847 alarm_control_panel::AlarmControlPanelCall::*) (const char *, size_t)>(&decltype(call)::set_code));
1848
1849 // Lookup table for alarm control panel methods
1850 static const struct {
1851 const char *name;
1853 } METHODS[] = {
1859 };
1860
1861 bool found = false;
1862 for (const auto &method : METHODS) {
1863 if (match.method_equals(method.name)) {
1864 (call.*method.action)();
1865 found = true;
1866 break;
1867 }
1868 }
1869
1870 if (!found) {
1871 request->send(404);
1872 return;
1873 }
1874
1875 DEFER_ACTION(call, call.perform());
1876 request->send(200);
1877 return;
1878 }
1879 request->send(404);
1880}
1882 return web_server->alarm_control_panel_json_((alarm_control_panel::AlarmControlPanel *) (source),
1883 ((alarm_control_panel::AlarmControlPanel *) (source))->get_state(),
1884 DETAIL_STATE);
1885}
1887 return web_server->alarm_control_panel_json_((alarm_control_panel::AlarmControlPanel *) (source),
1888 ((alarm_control_panel::AlarmControlPanel *) (source))->get_state(),
1889 DETAIL_ALL);
1890}
1891json::SerializationBuffer<> WebServer::alarm_control_panel_json_(alarm_control_panel::AlarmControlPanel *obj,
1893 JsonDetail start_config) {
1894 json::JsonBuilder builder;
1895 JsonObject root = builder.root();
1896
1897 set_json_icon_state_value(root, obj, "alarm_control_panel",
1898 json_state_str(alarm_control_panel_state_to_string(value)), value, start_config);
1899 if (start_config == DETAIL_ALL) {
1900 this->add_sorting_info_(root, obj);
1901 }
1902
1903 return builder.serialize();
1904}
1905#endif
1906
1907#ifdef USE_WATER_HEATER
1909 if (!this->include_internal_ && obj->is_internal())
1910 return;
1911 this->events_.deferrable_send_state(obj, "state", water_heater_state_json_generator);
1912}
1913void WebServer::handle_water_heater_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1914 for (water_heater::WaterHeater *obj : App.get_water_heaters()) {
1915 auto entity_match = match.match_entity(obj);
1916 if (!entity_match.matched)
1917 continue;
1918
1919 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
1920 auto detail = get_request_detail(request);
1921 auto data = this->water_heater_json_(obj, detail);
1922 request->send(200, "application/json", data.c_str());
1923 return;
1924 }
1925 if (!match.method_equals(ESPHOME_F("set"))) {
1926 request->send(404);
1927 return;
1928 }
1929 auto call = obj->make_call();
1930 // Use base class reference for template deduction (make_call returns WaterHeaterCallInternal)
1932
1933 // Parse mode parameter
1935 request, ESPHOME_F("mode"), base_call,
1936 static_cast<water_heater::WaterHeaterCall &(water_heater::WaterHeaterCall::*) (const char *, size_t)>(
1938
1939 // Parse temperature parameters
1940 parse_num_param_(request, ESPHOME_F("target_temperature"), base_call,
1942 parse_num_param_(request, ESPHOME_F("target_temperature_low"), base_call,
1944 parse_num_param_(request, ESPHOME_F("target_temperature_high"), base_call,
1946
1947 // Parse away mode parameter
1948 parse_bool_param_(request, ESPHOME_F("away"), base_call, &water_heater::WaterHeaterCall::set_away);
1949
1950 // Parse on/off parameter
1951 parse_bool_param_(request, ESPHOME_F("is_on"), base_call, &water_heater::WaterHeaterCall::set_on);
1952
1953 DEFER_ACTION(call, call.perform());
1954 request->send(200);
1955 return;
1956 }
1957 request->send(404);
1958}
1959
1961 return web_server->water_heater_json_(static_cast<water_heater::WaterHeater *>(source), DETAIL_STATE);
1962}
1964 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
1965 return web_server->water_heater_json_(static_cast<water_heater::WaterHeater *>(source), DETAIL_ALL);
1966}
1967json::SerializationBuffer<> WebServer::water_heater_json_(water_heater::WaterHeater *obj, JsonDetail start_config) {
1968 json::JsonBuilder builder;
1969 JsonObject root = builder.root();
1970
1971 const auto mode = obj->get_mode();
1973
1974 set_json_icon_state_value(root, obj, "water_heater", mode_s, mode, start_config);
1975
1976 auto traits = obj->get_traits();
1977
1978 if (start_config == DETAIL_ALL) {
1979 JsonArray modes = root[ESPHOME_F("modes")].to<JsonArray>();
1980 for (auto m : traits.get_supported_modes())
1981 modes.add(json_state_str(water_heater::water_heater_mode_to_string(m)));
1982 root[ESPHOME_F("min_temp")] = traits.get_min_temperature();
1983 root[ESPHOME_F("max_temp")] = traits.get_max_temperature();
1984 root[ESPHOME_F("step")] = traits.get_target_temperature_step();
1985 this->add_sorting_info_(root, obj);
1986 }
1987
1988 if (traits.get_supports_current_temperature()) {
1989 float current = obj->get_current_temperature();
1990 if (!std::isnan(current))
1991 root[ESPHOME_F("current_temperature")] = current;
1992 }
1993
1994 if (traits.get_supports_two_point_target_temperature()) {
1995 float low = obj->get_target_temperature_low();
1996 float high = obj->get_target_temperature_high();
1997 if (!std::isnan(low))
1998 root[ESPHOME_F("target_temperature_low")] = low;
1999 if (!std::isnan(high))
2000 root[ESPHOME_F("target_temperature_high")] = high;
2001 } else {
2002 float target = obj->get_target_temperature();
2003 if (!std::isnan(target))
2004 root[ESPHOME_F("target_temperature")] = target;
2005 }
2006
2007 if (traits.get_supports_away_mode()) {
2008 root[ESPHOME_F("away")] = obj->is_away();
2009 }
2010
2011 if (traits.has_feature_flags(water_heater::WATER_HEATER_SUPPORTS_ON_OFF)) {
2012 root[ESPHOME_F("is_on")] = obj->is_on();
2013 }
2014
2015 return builder.serialize();
2016}
2017#endif
2018
2019#ifdef USE_INFRARED
2020void WebServer::handle_infrared_request(AsyncWebServerRequest *request, const UrlMatch &match) {
2021 for (infrared::Infrared *obj : App.get_infrareds()) {
2022 auto entity_match = match.match_entity(obj);
2023 if (!entity_match.matched)
2024 continue;
2025
2026 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
2027 auto detail = get_request_detail(request);
2028 auto data = this->infrared_json_(obj, detail);
2029 request->send(200, ESPHOME_F("application/json"), data.c_str());
2030 return;
2031 }
2032 if (!match.method_equals(ESPHOME_F("transmit"))) {
2033 request->send(404);
2034 return;
2035 }
2036
2037 // Only allow transmit if the device supports it
2038 if (!obj->has_transmitter()) {
2039 request->send(400, ESPHOME_F("text/plain"), ESPHOME_F("Device does not support transmission"));
2040 return;
2041 }
2042
2043 // Parse parameters
2044 auto call = obj->make_call();
2045
2046 // Parse carrier frequency (optional)
2047 {
2048 auto value = parse_number<uint32_t>(request->arg(ESPHOME_F("carrier_frequency")).c_str());
2049 if (value.has_value()) {
2050 call.set_carrier_frequency(*value);
2051 }
2052 }
2053
2054 // Parse repeat count (optional, defaults to 1)
2055 {
2056 auto value = parse_number<uint32_t>(request->arg(ESPHOME_F("repeat_count")).c_str());
2057 if (value.has_value()) {
2058 call.set_repeat_count(*value);
2059 }
2060 }
2061
2062 // Parse base64url-encoded raw timings (required)
2063 // Base64url is URL-safe: uses A-Za-z0-9-_ (no special characters needing escaping)
2064 const auto &data_arg = request->arg(ESPHOME_F("data"));
2065
2066 // Validate base64url is not empty (also catches missing parameter since arg() returns empty string)
2067 // Arduino String has isEmpty() not empty(), use length() for cross-platform compatibility
2068 if (data_arg.length() == 0) { // NOLINT(readability-container-size-empty)
2069 request->send(400, ESPHOME_F("text/plain"), ESPHOME_F("Missing or empty 'data' parameter"));
2070 return;
2071 }
2072
2073 // Defer to main loop for thread safety. Move encoded string into lambda to ensure
2074 // it outlives the call - set_raw_timings_base64url stores a pointer, so the string
2075 // must remain valid until perform() completes.
2076 // ESP8266 also needs this because ESPAsyncWebServer callbacks run in "sys" context.
2077 this->defer([call, encoded = std::string(data_arg.c_str(), data_arg.length())]() mutable {
2078 call.set_raw_timings_base64url(encoded);
2079 call.perform();
2080 });
2081
2082 request->send(200);
2083 return;
2084 }
2085 request->send(404);
2086}
2087
2089 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
2090 return web_server->infrared_json_(static_cast<infrared::Infrared *>(source), DETAIL_ALL);
2091}
2092
2093json::SerializationBuffer<> WebServer::infrared_json_(infrared::Infrared *obj, JsonDetail start_config) {
2094 json::JsonBuilder builder;
2095 JsonObject root = builder.root();
2096
2097 set_json_icon_state_value(root, obj, "infrared", "", 0, start_config);
2098
2099 auto traits = obj->get_traits();
2100
2101 root[ESPHOME_F("supports_transmitter")] = traits.get_supports_transmitter();
2102 root[ESPHOME_F("supports_receiver")] = traits.get_supports_receiver();
2103
2104 if (start_config == DETAIL_ALL) {
2105 this->add_sorting_info_(root, obj);
2106 }
2107
2108 return builder.serialize();
2109}
2110#endif
2111
2112#ifdef USE_RADIO_FREQUENCY
2113void WebServer::handle_radio_frequency_request(AsyncWebServerRequest *request, const UrlMatch &match) {
2114 for (radio_frequency::RadioFrequency *obj : App.get_radio_frequencies()) {
2115 auto entity_match = match.match_entity(obj);
2116 if (!entity_match.matched)
2117 continue;
2118
2119 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
2120 auto detail = get_request_detail(request);
2121 auto data = this->radio_frequency_json_(obj, detail);
2122 request->send(200, ESPHOME_F("application/json"), data.c_str());
2123 return;
2124 }
2125 if (!match.method_equals(ESPHOME_F("transmit"))) {
2126 request->send(404);
2127 return;
2128 }
2129
2130 // Only allow transmit if the device supports it
2132 request->send(400, ESPHOME_F("text/plain"), ESPHOME_F("Device does not support transmission"));
2133 return;
2134 }
2135
2136 auto call = obj->make_call();
2137
2138 // Parse carrier frequency (optional — overrides IC default)
2139 {
2140 auto value = parse_number<uint32_t>(request->arg(ESPHOME_F("frequency")).c_str());
2141 if (value.has_value()) {
2142 call.set_frequency(*value);
2143 }
2144 }
2145
2146 // Parse repeat count (optional, defaults to 1)
2147 {
2148 auto value = parse_number<uint32_t>(request->arg(ESPHOME_F("repeat_count")).c_str());
2149 if (value.has_value()) {
2150 call.set_repeat_count(*value);
2151 }
2152 }
2153
2154 // Parse base64url-encoded raw timings (required)
2155 // Base64url is URL-safe: uses A-Za-z0-9-_ (no special characters needing escaping)
2156 const auto &data_arg = request->arg(ESPHOME_F("data"));
2157
2158 // Validate base64url is not empty (also catches missing parameter since arg() returns empty string)
2159 // Arduino String has isEmpty() not empty(), use length() for cross-platform compatibility
2160 if (data_arg.length() == 0) { // NOLINT(readability-container-size-empty)
2161 request->send(400, ESPHOME_F("text/plain"), ESPHOME_F("Missing or empty 'data' parameter"));
2162 return;
2163 }
2164
2165 // Defer to main loop for thread safety. Move encoded string into lambda to ensure
2166 // it outlives the call - set_raw_timings_base64url stores a pointer, so the string
2167 // must remain valid until perform() completes.
2168 // ESP8266 also needs this because ESPAsyncWebServer callbacks run in "sys" context.
2169 this->defer([call, encoded = std::string(data_arg.c_str(), data_arg.length())]() mutable {
2170 call.set_raw_timings_base64url(encoded);
2171 call.perform();
2172 });
2173
2174 request->send(200);
2175 return;
2176 }
2177 request->send(404);
2178}
2179
2181 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
2182 return web_server->radio_frequency_json_(static_cast<radio_frequency::RadioFrequency *>(source), DETAIL_ALL);
2183}
2184
2185json::SerializationBuffer<> WebServer::radio_frequency_json_(radio_frequency::RadioFrequency *obj,
2186 JsonDetail start_config) {
2187 json::JsonBuilder builder;
2188 JsonObject root = builder.root();
2189
2190 set_json_icon_state_value(root, obj, "radio_frequency", "", 0, start_config);
2191
2192 const auto &traits = obj->get_traits();
2193 auto caps = obj->get_capability_flags();
2194
2195 root[ESPHOME_F("supports_transmitter")] = bool(caps & radio_frequency::CAPABILITY_TRANSMITTER);
2196 root[ESPHOME_F("supports_receiver")] = bool(caps & radio_frequency::CAPABILITY_RECEIVER);
2197 if (traits.get_frequency_min_hz() != 0) {
2198 root[ESPHOME_F("frequency_min")] = traits.get_frequency_min_hz();
2199 root[ESPHOME_F("frequency_max")] = traits.get_frequency_max_hz();
2200 }
2201
2202 if (start_config == DETAIL_ALL) {
2203 this->add_sorting_info_(root, obj);
2204 }
2205
2206 return builder.serialize();
2207}
2208#endif
2209
2210#ifdef USE_EVENT
2212 if (!this->include_internal_ && obj->is_internal())
2213 return;
2214 this->events_.deferrable_send_state(obj, "state", event_state_json_generator);
2215}
2216
2217void WebServer::handle_event_request(AsyncWebServerRequest *request, const UrlMatch &match) {
2218 for (event::Event *obj : App.get_events()) {
2219 auto entity_match = match.match_entity(obj);
2220 if (!entity_match.matched)
2221 continue;
2222
2223 // Note: request->method() is always HTTP_GET here (canHandle ensures this)
2224 if (entity_match.action_is_empty) {
2225 auto detail = get_request_detail(request);
2226 auto data = this->event_json_(obj, StringRef(), detail);
2227 request->send(200, "application/json", data.c_str());
2228 return;
2229 }
2230 }
2231 request->send(404);
2232}
2233
2234static StringRef get_event_type(event::Event *event) { return event ? event->get_last_event_type() : StringRef(); }
2235
2237 auto *event = static_cast<event::Event *>(source);
2238 return web_server->event_json_(event, get_event_type(event), DETAIL_STATE);
2239}
2240// NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
2242 auto *event = static_cast<event::Event *>(source);
2243 return web_server->event_json_(event, get_event_type(event), DETAIL_ALL);
2244}
2245json::SerializationBuffer<> WebServer::event_json_(event::Event *obj, StringRef event_type, JsonDetail start_config) {
2246 json::JsonBuilder builder;
2247 JsonObject root = builder.root();
2248
2249 set_json_id(root, obj, "event", start_config);
2250 if (!event_type.empty()) {
2251 root[ESPHOME_F("event_type")] = event_type;
2252 }
2253 if (start_config == DETAIL_ALL) {
2254 JsonArray event_types = root[ESPHOME_F("event_types")].to<JsonArray>();
2255 for (const char *event_type : obj->get_event_types()) {
2256 event_types.add(event_type);
2257 }
2258 char dc_buf[MAX_DEVICE_CLASS_LENGTH];
2259 root[ESPHOME_F("device_class")] = obj->get_device_class_to(dc_buf);
2260 this->add_sorting_info_(root, obj);
2261 }
2262
2263 return builder.serialize();
2264}
2265// NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
2266#endif
2267
2268#ifdef USE_UPDATE
2270 this->events_.deferrable_send_state(obj, "state", update_state_json_generator);
2271}
2272void WebServer::handle_update_request(AsyncWebServerRequest *request, const UrlMatch &match) {
2273 for (update::UpdateEntity *obj : App.get_updates()) {
2274 auto entity_match = match.match_entity(obj);
2275 if (!entity_match.matched)
2276 continue;
2277
2278 if (request->method() == HTTP_GET && entity_match.action_is_empty) {
2279 auto detail = get_request_detail(request);
2280 auto data = this->update_json_(obj, detail);
2281 request->send(200, "application/json", data.c_str());
2282 return;
2283 }
2284
2285 if (!match.method_equals(ESPHOME_F("install"))) {
2286 request->send(404);
2287 return;
2288 }
2289
2290 DEFER_ACTION(obj, obj->perform());
2291 request->send(200);
2292 return;
2293 }
2294 request->send(404);
2295}
2297 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
2298 return web_server->update_json_((update::UpdateEntity *) (source), DETAIL_STATE);
2299}
2301 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
2302 return web_server->update_json_((update::UpdateEntity *) (source), DETAIL_ALL);
2303}
2304json::SerializationBuffer<> WebServer::update_json_(update::UpdateEntity *obj, JsonDetail start_config) {
2305 // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
2306 json::JsonBuilder builder;
2307 JsonObject root = builder.root();
2308
2309 set_json_icon_state_value(root, obj, "update", json_state_str(update::update_state_to_string(obj->state)),
2310 obj->update_info.latest_version, start_config);
2311 if (start_config == DETAIL_ALL) {
2312 root[ESPHOME_F("current_version")] = obj->update_info.current_version;
2313 root[ESPHOME_F("title")] = obj->update_info.title;
2314 // Truncate long changelogs — full text available via release_url
2315 constexpr size_t max_summary_len = 256;
2316 root[ESPHOME_F("summary")] = obj->update_info.summary.size() <= max_summary_len
2317 ? obj->update_info.summary
2318 : obj->update_info.summary.substr(0, max_summary_len);
2319 root[ESPHOME_F("release_url")] = obj->update_info.release_url;
2320 this->add_sorting_info_(root, obj);
2321 }
2322
2323 return builder.serialize();
2324 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
2325}
2326#endif
2327
2328bool WebServer::canHandle(AsyncWebServerRequest *request) const {
2329#ifdef USE_ESP32
2330 char url_buf[AsyncWebServerRequest::URL_BUF_SIZE];
2331 StringRef url = request->url_to(url_buf);
2332#else
2333 const auto &url = request->url();
2334#endif
2335 const auto method = request->method();
2336
2337 // Static URL checks - use ESPHOME_F to keep strings in flash on ESP8266
2338 if (url == ESPHOME_F("/"))
2339 return true;
2340#if !defined(USE_ESP32) && defined(USE_ARDUINO)
2341 if (url == ESPHOME_F("/events"))
2342 return true;
2343#endif
2344#ifdef USE_WEBSERVER_CSS_INCLUDE
2345 if (url == ESPHOME_F("/0.css"))
2346 return true;
2347#endif
2348#ifdef USE_WEBSERVER_JS_INCLUDE
2349 if (url == ESPHOME_F("/0.js"))
2350 return true;
2351#endif
2352
2353#ifdef USE_WEBSERVER_PRIVATE_NETWORK_ACCESS
2354 if (method == HTTP_OPTIONS && request->hasHeader(ESPHOME_F("Access-Control-Request-Private-Network")))
2355 return true;
2356#endif
2357
2358 // Parse URL for component checks
2359 UrlMatch match = match_url(url.c_str(), url.length(), true);
2360 if (!match.valid)
2361 return false;
2362
2363 // Common pattern check
2364 bool is_get = method == HTTP_GET;
2365 bool is_post = method == HTTP_POST;
2366 bool is_get_or_post = is_get || is_post;
2367
2368 if (!is_get_or_post)
2369 return false;
2370
2371 // Check GET-only domains - use ESPHOME_F to keep strings in flash on ESP8266
2372 if (is_get) {
2373#ifdef USE_SENSOR
2374 if (match.domain_equals(ESPHOME_F("sensor")))
2375 return true;
2376#endif
2377#ifdef USE_BINARY_SENSOR
2378 if (match.domain_equals(ESPHOME_F("binary_sensor")))
2379 return true;
2380#endif
2381#ifdef USE_TEXT_SENSOR
2382 if (match.domain_equals(ESPHOME_F("text_sensor")))
2383 return true;
2384#endif
2385#ifdef USE_EVENT
2386 if (match.domain_equals(ESPHOME_F("event")))
2387 return true;
2388#endif
2389 }
2390
2391 // Check GET+POST domains
2392 if (is_get_or_post) {
2393#ifdef USE_SWITCH
2394 if (match.domain_equals(ESPHOME_F("switch")))
2395 return true;
2396#endif
2397#ifdef USE_BUTTON
2398 if (match.domain_equals(ESPHOME_F("button")))
2399 return true;
2400#endif
2401#ifdef USE_FAN
2402 if (match.domain_equals(ESPHOME_F("fan")))
2403 return true;
2404#endif
2405#ifdef USE_LIGHT
2406 if (match.domain_equals(ESPHOME_F("light")))
2407 return true;
2408#endif
2409#ifdef USE_COVER
2410 if (match.domain_equals(ESPHOME_F("cover")))
2411 return true;
2412#endif
2413#ifdef USE_NUMBER
2414 if (match.domain_equals(ESPHOME_F("number")))
2415 return true;
2416#endif
2417#ifdef USE_DATETIME_DATE
2418 if (match.domain_equals(ESPHOME_F("date")))
2419 return true;
2420#endif
2421#ifdef USE_DATETIME_TIME
2422 if (match.domain_equals(ESPHOME_F("time")))
2423 return true;
2424#endif
2425#ifdef USE_DATETIME_DATETIME
2426 if (match.domain_equals(ESPHOME_F("datetime")))
2427 return true;
2428#endif
2429#ifdef USE_TEXT
2430 if (match.domain_equals(ESPHOME_F("text")))
2431 return true;
2432#endif
2433#ifdef USE_SELECT
2434 if (match.domain_equals(ESPHOME_F("select")))
2435 return true;
2436#endif
2437#ifdef USE_CLIMATE
2438 if (match.domain_equals(ESPHOME_F("climate")))
2439 return true;
2440#endif
2441#ifdef USE_LOCK
2442 if (match.domain_equals(ESPHOME_F("lock")))
2443 return true;
2444#endif
2445#ifdef USE_VALVE
2446 if (match.domain_equals(ESPHOME_F("valve")))
2447 return true;
2448#endif
2449#ifdef USE_ALARM_CONTROL_PANEL
2450 if (match.domain_equals(ESPHOME_F("alarm_control_panel")))
2451 return true;
2452#endif
2453#ifdef USE_UPDATE
2454 if (match.domain_equals(ESPHOME_F("update")))
2455 return true;
2456#endif
2457#ifdef USE_WATER_HEATER
2458 if (match.domain_equals(ESPHOME_F("water_heater")))
2459 return true;
2460#endif
2461#ifdef USE_INFRARED
2462 if (match.domain_equals(ESPHOME_F("infrared")))
2463 return true;
2464#endif
2465#ifdef USE_RADIO_FREQUENCY
2466 if (match.domain_equals(ESPHOME_F("radio_frequency")))
2467 return true;
2468#endif
2469 }
2470
2471 return false;
2472}
2473void WebServer::handleRequest(AsyncWebServerRequest *request) {
2474#ifdef USE_ESP32
2475 char url_buf[AsyncWebServerRequest::URL_BUF_SIZE];
2476 StringRef url = request->url_to(url_buf);
2477#else
2478 const auto &url = request->url();
2479#endif
2480
2481 // Handle static routes first
2482 if (url == ESPHOME_F("/")) {
2483 this->handle_index_request(request);
2484 return;
2485 }
2486
2487#ifdef USE_WEBSERVER_PRIVATE_NETWORK_ACCESS
2488 // Private Network Access preflight carries a cross-origin Origin by design; its handler does the
2489 // origin check itself, so let it run before the general enforcement below.
2490 if (request->method() == HTTP_OPTIONS && request->hasHeader(ESPHOME_F("Access-Control-Request-Private-Network"))) {
2491 this->handle_pna_cors_request(request);
2492 return;
2493 }
2494#endif
2495
2496 // Reject cross-origin browser requests unless the origin is explicitly allowed.
2497 if (!this->is_request_origin_allowed_(request, get_request_header(request, "Origin"))) {
2498 request->send(403);
2499 return;
2500 }
2501
2502#if !defined(USE_ESP32) && defined(USE_ARDUINO)
2503 if (url == ESPHOME_F("/events")) {
2504 this->events_.add_new_client(this, request);
2505 return;
2506 }
2507#endif
2508
2509#ifdef USE_WEBSERVER_CSS_INCLUDE
2510 if (url == ESPHOME_F("/0.css")) {
2511 this->handle_css_request(request);
2512 return;
2513 }
2514#endif
2515
2516#ifdef USE_WEBSERVER_JS_INCLUDE
2517 if (url == ESPHOME_F("/0.js")) {
2518 this->handle_js_request(request);
2519 return;
2520 }
2521#endif
2522
2523 // Parse URL for component routing
2524 // Pass HTTP method to disambiguate 3-segment URLs (GET=sub-device state, POST=main device action)
2525 UrlMatch match = match_url(url.c_str(), url.length(), false, request->method() == HTTP_POST);
2526
2527 // Route to appropriate handler based on domain
2528 // NOLINTNEXTLINE(readability-simplify-boolean-expr)
2529 if (false) { // Start chain for else-if macro pattern
2530 }
2531#ifdef USE_SENSOR
2532 else if (match.domain_equals(ESPHOME_F("sensor"))) {
2533 this->handle_sensor_request(request, match);
2534 }
2535#endif
2536#ifdef USE_SWITCH
2537 else if (match.domain_equals(ESPHOME_F("switch"))) {
2538 this->handle_switch_request(request, match);
2539 }
2540#endif
2541#ifdef USE_BUTTON
2542 else if (match.domain_equals(ESPHOME_F("button"))) {
2543 this->handle_button_request(request, match);
2544 }
2545#endif
2546#ifdef USE_BINARY_SENSOR
2547 else if (match.domain_equals(ESPHOME_F("binary_sensor"))) {
2548 this->handle_binary_sensor_request(request, match);
2549 }
2550#endif
2551#ifdef USE_FAN
2552 else if (match.domain_equals(ESPHOME_F("fan"))) {
2553 this->handle_fan_request(request, match);
2554 }
2555#endif
2556#ifdef USE_LIGHT
2557 else if (match.domain_equals(ESPHOME_F("light"))) {
2558 this->handle_light_request(request, match);
2559 }
2560#endif
2561#ifdef USE_TEXT_SENSOR
2562 else if (match.domain_equals(ESPHOME_F("text_sensor"))) {
2563 this->handle_text_sensor_request(request, match);
2564 }
2565#endif
2566#ifdef USE_COVER
2567 else if (match.domain_equals(ESPHOME_F("cover"))) {
2568 this->handle_cover_request(request, match);
2569 }
2570#endif
2571#ifdef USE_NUMBER
2572 else if (match.domain_equals(ESPHOME_F("number"))) {
2573 this->handle_number_request(request, match);
2574 }
2575#endif
2576#ifdef USE_DATETIME_DATE
2577 else if (match.domain_equals(ESPHOME_F("date"))) {
2578 this->handle_date_request(request, match);
2579 }
2580#endif
2581#ifdef USE_DATETIME_TIME
2582 else if (match.domain_equals(ESPHOME_F("time"))) {
2583 this->handle_time_request(request, match);
2584 }
2585#endif
2586#ifdef USE_DATETIME_DATETIME
2587 else if (match.domain_equals(ESPHOME_F("datetime"))) {
2588 this->handle_datetime_request(request, match);
2589 }
2590#endif
2591#ifdef USE_TEXT
2592 else if (match.domain_equals(ESPHOME_F("text"))) {
2593 this->handle_text_request(request, match);
2594 }
2595#endif
2596#ifdef USE_SELECT
2597 else if (match.domain_equals(ESPHOME_F("select"))) {
2598 this->handle_select_request(request, match);
2599 }
2600#endif
2601#ifdef USE_CLIMATE
2602 else if (match.domain_equals(ESPHOME_F("climate"))) {
2603 this->handle_climate_request(request, match);
2604 }
2605#endif
2606#ifdef USE_LOCK
2607 else if (match.domain_equals(ESPHOME_F("lock"))) {
2608 this->handle_lock_request(request, match);
2609 }
2610#endif
2611#ifdef USE_VALVE
2612 else if (match.domain_equals(ESPHOME_F("valve"))) {
2613 this->handle_valve_request(request, match);
2614 }
2615#endif
2616#ifdef USE_ALARM_CONTROL_PANEL
2617 else if (match.domain_equals(ESPHOME_F("alarm_control_panel"))) {
2618 this->handle_alarm_control_panel_request(request, match);
2619 }
2620#endif
2621#ifdef USE_UPDATE
2622 else if (match.domain_equals(ESPHOME_F("update"))) {
2623 this->handle_update_request(request, match);
2624 }
2625#endif
2626#ifdef USE_WATER_HEATER
2627 else if (match.domain_equals(ESPHOME_F("water_heater"))) {
2628 this->handle_water_heater_request(request, match);
2629 }
2630#endif
2631#ifdef USE_INFRARED
2632 else if (match.domain_equals(ESPHOME_F("infrared"))) {
2633 this->handle_infrared_request(request, match);
2634 }
2635#endif
2636#ifdef USE_RADIO_FREQUENCY
2637 else if (match.domain_equals(ESPHOME_F("radio_frequency"))) {
2638 this->handle_radio_frequency_request(request, match);
2639 }
2640#endif
2641 else {
2642 // No matching handler found - send 404
2643 ESP_LOGV(TAG, "Request for unknown URL: %s", url.c_str());
2644 request->send(404, ESPHOME_F("text/plain"), ESPHOME_F("Not Found"));
2645 }
2646}
2647
2648bool WebServer::isRequestHandlerTrivial() const { return false; }
2649
2650void WebServer::add_sorting_info_(JsonObject &root, EntityBase *entity) {
2651#ifdef USE_WEBSERVER_SORTING
2652 if (this->sorting_entitys_.contains(entity)) {
2653 root[ESPHOME_F("sorting_weight")] = this->sorting_entitys_[entity].weight;
2654 if (this->sorting_groups_.contains(this->sorting_entitys_[entity].group_id)) {
2655 root[ESPHOME_F("sorting_group")] = this->sorting_groups_[this->sorting_entitys_[entity].group_id].name;
2656 }
2657 }
2658#endif
2659}
2660
2661#ifdef USE_WEBSERVER_SORTING
2662void WebServer::add_entity_config(EntityBase *entity, float weight, uint64_t group) {
2663 this->sorting_entitys_[entity] = SortingComponents{weight, group};
2664}
2665
2666void WebServer::add_sorting_group(uint64_t group_id, const std::string &group_name, float weight) {
2667 this->sorting_groups_[group_id] = SortingGroup{group_name, weight};
2668}
2669#endif
2670
2671} // namespace esphome::web_server
2672#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
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:25
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:473
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:400
const void size_t len
Definition hal.h:64
if(written< 0)
Definition helpers.h:1061
optional< T > parse_number(const char *str)
Parse an unsigned decimal number from a null-terminated string.
Definition helpers.h:1157
int8_t step_to_accuracy_decimals(float step)
Derive accuracy in decimals from an increment step.
Definition helpers.cpp:503
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:750
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:492
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:1567
@ PARSE_TOGGLE
Definition helpers.h:1569
@ PARSE_OFF
Definition helpers.h:1568
@ PARSE_NONE
Definition helpers.h:1566
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