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