ESPHome 2025.9.0-dev
Loading...
Searching...
No Matches
web_server.cpp
Go to the documentation of this file.
1#include "web_server.h"
2#ifdef USE_WEBSERVER
8#include "esphome/core/log.h"
9#include "esphome/core/util.h"
10
11#ifdef USE_ARDUINO
12#include "StreamString.h"
13#endif
14
15#include <cstdlib>
16
17#ifdef USE_LIGHT
19#endif
20
21#ifdef USE_LOGGER
23#endif
24
25#ifdef USE_CLIMATE
27#endif
28
29#ifdef USE_WEBSERVER_LOCAL
30#if USE_WEBSERVER_VERSION == 2
31#include "server_index_v2.h"
32#elif USE_WEBSERVER_VERSION == 3
33#include "server_index_v3.h"
34#endif
35#endif
36
37namespace esphome {
38namespace web_server {
39
40static const char *const TAG = "web_server";
41
42#ifdef USE_WEBSERVER_PRIVATE_NETWORK_ACCESS
43static const char *const HEADER_PNA_NAME = "Private-Network-Access-Name";
44static const char *const HEADER_PNA_ID = "Private-Network-Access-ID";
45static const char *const HEADER_CORS_REQ_PNA = "Access-Control-Request-Private-Network";
46static const char *const HEADER_CORS_ALLOW_PNA = "Access-Control-Allow-Private-Network";
47#endif
48
49// Parse URL and return match info
50static UrlMatch match_url(const char *url_ptr, size_t url_len, bool only_domain) {
51 UrlMatch match{};
52
53 // URL must start with '/'
54 if (url_len < 2 || url_ptr[0] != '/') {
55 return match;
56 }
57
58 // Skip leading '/'
59 const char *start = url_ptr + 1;
60 const char *end = url_ptr + url_len;
61
62 // Find domain (everything up to next '/' or end)
63 const char *domain_end = (const char *) memchr(start, '/', end - start);
64 if (!domain_end) {
65 // No second slash found - original behavior returns invalid
66 return match;
67 }
68
69 // Set domain
70 match.domain = start;
71 match.domain_len = domain_end - start;
72 match.valid = true;
73
74 if (only_domain) {
75 return match;
76 }
77
78 // Parse ID if present
79 if (domain_end + 1 >= end) {
80 return match; // Nothing after domain slash
81 }
82
83 const char *id_start = domain_end + 1;
84 const char *id_end = (const char *) memchr(id_start, '/', end - id_start);
85
86 if (!id_end) {
87 // No more slashes, entire remaining string is ID
88 match.id = id_start;
89 match.id_len = end - id_start;
90 return match;
91 }
92
93 // Set ID
94 match.id = id_start;
95 match.id_len = id_end - id_start;
96
97 // Parse method if present
98 if (id_end + 1 < end) {
99 match.method = id_end + 1;
100 match.method_len = end - (id_end + 1);
101 }
102
103 return match;
104}
105
106#ifdef USE_ARDUINO
107// helper for allowing only unique entries in the queue
109 DeferredEvent item(source, message_generator);
110
111 auto iter = std::find_if(this->deferred_queue_.begin(), this->deferred_queue_.end(),
112 [&item](const DeferredEvent &test) -> bool { return test == item; });
113
114 if (iter != this->deferred_queue_.end()) {
115 (*iter) = item;
116 } else {
117 this->deferred_queue_.push_back(item);
118 }
119}
120
122 while (!deferred_queue_.empty()) {
123 DeferredEvent &de = deferred_queue_.front();
124 std::string message = de.message_generator_(web_server_, de.source_);
125 if (this->send(message.c_str(), "state") != DISCARDED) {
126 // O(n) but memory efficiency is more important than speed here which is why std::vector was chosen
127 deferred_queue_.erase(deferred_queue_.begin());
128 this->consecutive_send_failures_ = 0; // Reset failure count on successful send
129 } else {
132 // Too many failures, connection is likely dead
133 ESP_LOGW(TAG, "Closing stuck EventSource connection after %" PRIu16 " failed sends",
135 this->close();
136 this->deferred_queue_.clear();
137 }
138 break;
139 }
140 }
141}
142
148
149void DeferredUpdateEventSource::deferrable_send_state(void *source, const char *event_type,
150 message_generator_t *message_generator) {
151 // allow all json "details_all" to go through before publishing bare state events, this avoids unnamed entries showing
152 // up in the web GUI and reduces event load during initial connect
153 if (!entities_iterator_.completed() && 0 != strcmp(event_type, "state_detail_all"))
154 return;
155
156 if (source == nullptr)
157 return;
158 if (event_type == nullptr)
159 return;
160 if (message_generator == nullptr)
161 return;
162
163 if (0 != strcmp(event_type, "state_detail_all") && 0 != strcmp(event_type, "state")) {
164 ESP_LOGE(TAG, "Can't defer non-state event");
165 }
166
167 if (!deferred_queue_.empty())
169 if (!deferred_queue_.empty()) {
170 // deferred queue still not empty which means downstream event queue full, no point trying to send first
171 deq_push_back_with_dedup_(source, message_generator);
172 } else {
173 std::string message = message_generator(web_server_, source);
174 if (this->send(message.c_str(), "state") == DISCARDED) {
175 deq_push_back_with_dedup_(source, message_generator);
176 } else {
177 this->consecutive_send_failures_ = 0; // Reset failure count on successful send
178 }
179 }
180}
181
182// used for logs plus the initial ping/config
183void DeferredUpdateEventSource::try_send_nodefer(const char *message, const char *event, uint32_t id,
184 uint32_t reconnect) {
185 this->send(message, event, id, reconnect);
186}
187
189 for (DeferredUpdateEventSource *dues : *this) {
190 dues->loop();
191 }
192}
193
194void DeferredUpdateEventSourceList::deferrable_send_state(void *source, const char *event_type,
195 message_generator_t *message_generator) {
196 for (DeferredUpdateEventSource *dues : *this) {
197 dues->deferrable_send_state(source, event_type, message_generator);
198 }
199}
200
201void DeferredUpdateEventSourceList::try_send_nodefer(const char *message, const char *event, uint32_t id,
202 uint32_t reconnect) {
203 for (DeferredUpdateEventSource *dues : *this) {
204 dues->try_send_nodefer(message, event, id, reconnect);
205 }
206}
207
208void DeferredUpdateEventSourceList::add_new_client(WebServer *ws, AsyncWebServerRequest *request) {
210 this->push_back(es);
211
212 es->onConnect([this, ws, es](AsyncEventSourceClient *client) {
213 ws->defer([this, ws, es]() { this->on_client_connect_(ws, es); });
214 });
215
216 es->onDisconnect([this, ws, es](AsyncEventSourceClient *client) {
217 ws->defer([this, es]() { this->on_client_disconnect_((DeferredUpdateEventSource *) es); });
218 });
219
220 es->handleRequest(request);
221}
222
224 // Configure reconnect timeout and send config
225 // this should always go through since the AsyncEventSourceClient event queue is empty on connect
226 std::string message = ws->get_config_json();
227 source->try_send_nodefer(message.c_str(), "ping", millis(), 30000);
228
229#ifdef USE_WEBSERVER_SORTING
230 for (auto &group : ws->sorting_groups_) {
231 message = json::build_json([group](JsonObject root) {
232 root["name"] = group.second.name;
233 root["sorting_weight"] = group.second.weight;
234 });
235
236 // up to 31 groups should be able to be queued initially without defer
237 source->try_send_nodefer(message.c_str(), "sorting_group");
238 }
239#endif
240
242
243 // just dump them all up-front and take advantage of the deferred queue
244 // on second thought that takes too long, but leaving the commented code here for debug purposes
245 // while(!source->entities_iterator_.completed()) {
246 // source->entities_iterator_.advance();
247 //}
248}
249
251 // This method was called via WebServer->defer() and is no longer executing in the
252 // context of the network callback. The object is now dead and can be safely deleted.
253 this->remove(source);
254 delete source; // NOLINT
255}
256#endif
257
259
260#ifdef USE_WEBSERVER_CSS_INCLUDE
261void WebServer::set_css_include(const char *css_include) { this->css_include_ = css_include; }
262#endif
263#ifdef USE_WEBSERVER_JS_INCLUDE
264void WebServer::set_js_include(const char *js_include) { this->js_include_ = js_include; }
265#endif
266
268 return json::build_json([this](JsonObject root) {
269 root["title"] = App.get_friendly_name().empty() ? App.get_name() : App.get_friendly_name();
270 root["comment"] = App.get_comment();
271#if defined(USE_WEBSERVER_OTA_DISABLED) || !defined(USE_WEBSERVER_OTA)
272 root["ota"] = false; // Note: USE_WEBSERVER_OTA_DISABLED only affects web_server, not captive_portal
273#else
274 root["ota"] = true;
275#endif
276 root["log"] = this->expose_log_;
277 root["lang"] = "en";
278 });
279}
280
283 this->base_->init();
284
285#ifdef USE_LOGGER
286 if (logger::global_logger != nullptr && this->expose_log_) {
288 // logs are not deferred, the memory overhead would be too large
289 [this](int level, const char *tag, const char *message, size_t message_len) {
290 (void) message_len;
291 this->events_.try_send_nodefer(message, "log", millis());
292 });
293 }
294#endif
295
296#ifdef USE_ESP_IDF
297 this->base_->add_handler(&this->events_);
298#endif
299 this->base_->add_handler(this);
300
301 // OTA is now handled by the web_server OTA platform
302
303 // doesn't need defer functionality - if the queue is full, the client JS knows it's alive because it's clearly
304 // getting a lot of events
305 this->set_interval(10000, [this]() { this->events_.try_send_nodefer("", "ping", millis(), 30000); });
306}
307void WebServer::loop() { this->events_.loop(); }
309 ESP_LOGCONFIG(TAG,
310 "Web Server:\n"
311 " Address: %s:%u",
312 network::get_use_address().c_str(), this->base_->get_port());
313}
315
316#ifdef USE_WEBSERVER_LOCAL
317void WebServer::handle_index_request(AsyncWebServerRequest *request) {
318#ifndef USE_ESP8266
319 AsyncWebServerResponse *response = request->beginResponse(200, "text/html", INDEX_GZ, sizeof(INDEX_GZ));
320#else
321 AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", INDEX_GZ, sizeof(INDEX_GZ));
322#endif
323 response->addHeader("Content-Encoding", "gzip");
324 request->send(response);
325}
326#elif USE_WEBSERVER_VERSION >= 2
327void WebServer::handle_index_request(AsyncWebServerRequest *request) {
328#ifndef USE_ESP8266
329 AsyncWebServerResponse *response =
330 request->beginResponse(200, "text/html", ESPHOME_WEBSERVER_INDEX_HTML, ESPHOME_WEBSERVER_INDEX_HTML_SIZE);
331#else
332 AsyncWebServerResponse *response =
333 request->beginResponse_P(200, "text/html", ESPHOME_WEBSERVER_INDEX_HTML, ESPHOME_WEBSERVER_INDEX_HTML_SIZE);
334#endif
335 // No gzip header here because the HTML file is so small
336 request->send(response);
337}
338#endif
339
340#ifdef USE_WEBSERVER_PRIVATE_NETWORK_ACCESS
341void WebServer::handle_pna_cors_request(AsyncWebServerRequest *request) {
342 AsyncWebServerResponse *response = request->beginResponse(200, "");
343 response->addHeader(HEADER_CORS_ALLOW_PNA, "true");
344 response->addHeader(HEADER_PNA_NAME, App.get_name().c_str());
345 std::string mac = get_mac_address_pretty();
346 response->addHeader(HEADER_PNA_ID, mac.c_str());
347 request->send(response);
348}
349#endif
350
351#ifdef USE_WEBSERVER_CSS_INCLUDE
352void WebServer::handle_css_request(AsyncWebServerRequest *request) {
353#ifndef USE_ESP8266
354 AsyncWebServerResponse *response =
355 request->beginResponse(200, "text/css", ESPHOME_WEBSERVER_CSS_INCLUDE, ESPHOME_WEBSERVER_CSS_INCLUDE_SIZE);
356#else
357 AsyncWebServerResponse *response =
358 request->beginResponse_P(200, "text/css", ESPHOME_WEBSERVER_CSS_INCLUDE, ESPHOME_WEBSERVER_CSS_INCLUDE_SIZE);
359#endif
360 response->addHeader("Content-Encoding", "gzip");
361 request->send(response);
362}
363#endif
364
365#ifdef USE_WEBSERVER_JS_INCLUDE
366void WebServer::handle_js_request(AsyncWebServerRequest *request) {
367#ifndef USE_ESP8266
368 AsyncWebServerResponse *response =
369 request->beginResponse(200, "text/javascript", ESPHOME_WEBSERVER_JS_INCLUDE, ESPHOME_WEBSERVER_JS_INCLUDE_SIZE);
370#else
371 AsyncWebServerResponse *response =
372 request->beginResponse_P(200, "text/javascript", ESPHOME_WEBSERVER_JS_INCLUDE, ESPHOME_WEBSERVER_JS_INCLUDE_SIZE);
373#endif
374 response->addHeader("Content-Encoding", "gzip");
375 request->send(response);
376}
377#endif
378
379// Helper functions to reduce code size by avoiding macro expansion
380static void set_json_id(JsonObject &root, EntityBase *obj, const std::string &id, JsonDetail start_config) {
381 root["id"] = id;
382 if (start_config == DETAIL_ALL) {
383 root["name"] = obj->get_name();
384 root["icon"] = obj->get_icon();
385 root["entity_category"] = obj->get_entity_category();
386 bool is_disabled = obj->is_disabled_by_default();
387 if (is_disabled)
388 root["is_disabled_by_default"] = is_disabled;
389 }
390}
391
392template<typename T>
393static void set_json_value(JsonObject &root, EntityBase *obj, const std::string &id, const T &value,
394 JsonDetail start_config) {
395 set_json_id(root, obj, id, start_config);
396 root["value"] = value;
397}
398
399template<typename T>
400static void set_json_icon_state_value(JsonObject &root, EntityBase *obj, const std::string &id,
401 const std::string &state, const T &value, JsonDetail start_config) {
402 set_json_value(root, obj, id, value, start_config);
403 root["state"] = state;
404}
405
406// Helper to get request detail parameter
407static JsonDetail get_request_detail(AsyncWebServerRequest *request) {
408 auto *param = request->getParam("detail");
409 return (param && param->value() == "all") ? DETAIL_ALL : DETAIL_STATE;
410}
411
412#ifdef USE_SENSOR
414 if (this->events_.empty())
415 return;
417}
418void WebServer::handle_sensor_request(AsyncWebServerRequest *request, const UrlMatch &match) {
419 for (sensor::Sensor *obj : App.get_sensors()) {
420 if (!match.id_equals(obj->get_object_id()))
421 continue;
422 if (request->method() == HTTP_GET && match.method_empty()) {
423 auto detail = get_request_detail(request);
424 std::string data = this->sensor_json(obj, obj->state, detail);
425 request->send(200, "application/json", data.c_str());
426 return;
427 }
428 }
429 request->send(404);
430}
431std::string WebServer::sensor_state_json_generator(WebServer *web_server, void *source) {
432 return web_server->sensor_json((sensor::Sensor *) (source), ((sensor::Sensor *) (source))->state, DETAIL_STATE);
433}
434std::string WebServer::sensor_all_json_generator(WebServer *web_server, void *source) {
435 return web_server->sensor_json((sensor::Sensor *) (source), ((sensor::Sensor *) (source))->state, DETAIL_ALL);
436}
437std::string WebServer::sensor_json(sensor::Sensor *obj, float value, JsonDetail start_config) {
438 return json::build_json([this, obj, value, start_config](JsonObject root) {
439 std::string state;
440 if (std::isnan(value)) {
441 state = "NA";
442 } else {
444 if (!obj->get_unit_of_measurement().empty())
445 state += " " + obj->get_unit_of_measurement();
446 }
447 set_json_icon_state_value(root, obj, "sensor-" + obj->get_object_id(), state, value, start_config);
448 if (start_config == DETAIL_ALL) {
449 this->add_sorting_info_(root, obj);
450 if (!obj->get_unit_of_measurement().empty())
451 root["uom"] = obj->get_unit_of_measurement();
452 }
453 });
454}
455#endif
456
457#ifdef USE_TEXT_SENSOR
459 if (this->events_.empty())
460 return;
462}
463void WebServer::handle_text_sensor_request(AsyncWebServerRequest *request, const UrlMatch &match) {
464 for (text_sensor::TextSensor *obj : App.get_text_sensors()) {
465 if (!match.id_equals(obj->get_object_id()))
466 continue;
467 if (request->method() == HTTP_GET && match.method_empty()) {
468 auto detail = get_request_detail(request);
469 std::string data = this->text_sensor_json(obj, obj->state, detail);
470 request->send(200, "application/json", data.c_str());
471 return;
472 }
473 }
474 request->send(404);
475}
476std::string WebServer::text_sensor_state_json_generator(WebServer *web_server, void *source) {
477 return web_server->text_sensor_json((text_sensor::TextSensor *) (source),
479}
480std::string WebServer::text_sensor_all_json_generator(WebServer *web_server, void *source) {
481 return web_server->text_sensor_json((text_sensor::TextSensor *) (source),
482 ((text_sensor::TextSensor *) (source))->state, DETAIL_ALL);
483}
484std::string WebServer::text_sensor_json(text_sensor::TextSensor *obj, const std::string &value,
485 JsonDetail start_config) {
486 return json::build_json([this, obj, value, start_config](JsonObject root) {
487 set_json_icon_state_value(root, obj, "text_sensor-" + obj->get_object_id(), value, value, start_config);
488 if (start_config == DETAIL_ALL) {
489 this->add_sorting_info_(root, obj);
490 }
491 });
492}
493#endif
494
495#ifdef USE_SWITCH
497 if (this->events_.empty())
498 return;
500}
501void WebServer::handle_switch_request(AsyncWebServerRequest *request, const UrlMatch &match) {
502 for (switch_::Switch *obj : App.get_switches()) {
503 if (!match.id_equals(obj->get_object_id()))
504 continue;
505
506 if (request->method() == HTTP_GET && match.method_empty()) {
507 auto detail = get_request_detail(request);
508 std::string data = this->switch_json(obj, obj->state, detail);
509 request->send(200, "application/json", data.c_str());
510 } else if (match.method_equals("toggle")) {
511 this->defer([obj]() { obj->toggle(); });
512 request->send(200);
513 } else if (match.method_equals("turn_on")) {
514 this->defer([obj]() { obj->turn_on(); });
515 request->send(200);
516 } else if (match.method_equals("turn_off")) {
517 this->defer([obj]() { obj->turn_off(); });
518 request->send(200);
519 } else {
520 request->send(404);
521 }
522 return;
523 }
524 request->send(404);
525}
526std::string WebServer::switch_state_json_generator(WebServer *web_server, void *source) {
527 return web_server->switch_json((switch_::Switch *) (source), ((switch_::Switch *) (source))->state, DETAIL_STATE);
528}
529std::string WebServer::switch_all_json_generator(WebServer *web_server, void *source) {
530 return web_server->switch_json((switch_::Switch *) (source), ((switch_::Switch *) (source))->state, DETAIL_ALL);
531}
532std::string WebServer::switch_json(switch_::Switch *obj, bool value, JsonDetail start_config) {
533 return json::build_json([this, obj, value, start_config](JsonObject root) {
534 set_json_icon_state_value(root, obj, "switch-" + obj->get_object_id(), value ? "ON" : "OFF", value, start_config);
535 if (start_config == DETAIL_ALL) {
536 root["assumed_state"] = obj->assumed_state();
537 this->add_sorting_info_(root, obj);
538 }
539 });
540}
541#endif
542
543#ifdef USE_BUTTON
544void WebServer::handle_button_request(AsyncWebServerRequest *request, const UrlMatch &match) {
545 for (button::Button *obj : App.get_buttons()) {
546 if (!match.id_equals(obj->get_object_id()))
547 continue;
548 if (request->method() == HTTP_GET && match.method_empty()) {
549 auto detail = get_request_detail(request);
550 std::string data = this->button_json(obj, detail);
551 request->send(200, "application/json", data.c_str());
552 } else if (match.method_equals("press")) {
553 this->defer([obj]() { obj->press(); });
554 request->send(200);
555 return;
556 } else {
557 request->send(404);
558 }
559 return;
560 }
561 request->send(404);
562}
563std::string WebServer::button_state_json_generator(WebServer *web_server, void *source) {
564 return web_server->button_json((button::Button *) (source), DETAIL_STATE);
565}
566std::string WebServer::button_all_json_generator(WebServer *web_server, void *source) {
567 return web_server->button_json((button::Button *) (source), DETAIL_ALL);
568}
569std::string WebServer::button_json(button::Button *obj, JsonDetail start_config) {
570 return json::build_json([this, obj, start_config](JsonObject root) {
571 set_json_id(root, obj, "button-" + obj->get_object_id(), start_config);
572 if (start_config == DETAIL_ALL) {
573 this->add_sorting_info_(root, obj);
574 }
575 });
576}
577#endif
578
579#ifdef USE_BINARY_SENSOR
585void WebServer::handle_binary_sensor_request(AsyncWebServerRequest *request, const UrlMatch &match) {
587 if (!match.id_equals(obj->get_object_id()))
588 continue;
589 if (request->method() == HTTP_GET && match.method_empty()) {
590 auto detail = get_request_detail(request);
591 std::string data = this->binary_sensor_json(obj, obj->state, detail);
592 request->send(200, "application/json", data.c_str());
593 return;
594 }
595 }
596 request->send(404);
597}
598std::string WebServer::binary_sensor_state_json_generator(WebServer *web_server, void *source) {
599 return web_server->binary_sensor_json((binary_sensor::BinarySensor *) (source),
601}
602std::string WebServer::binary_sensor_all_json_generator(WebServer *web_server, void *source) {
603 return web_server->binary_sensor_json((binary_sensor::BinarySensor *) (source),
605}
606std::string WebServer::binary_sensor_json(binary_sensor::BinarySensor *obj, bool value, JsonDetail start_config) {
607 return json::build_json([this, obj, value, start_config](JsonObject root) {
608 set_json_icon_state_value(root, obj, "binary_sensor-" + obj->get_object_id(), value ? "ON" : "OFF", value,
609 start_config);
610 if (start_config == DETAIL_ALL) {
611 this->add_sorting_info_(root, obj);
612 }
613 });
614}
615#endif
616
617#ifdef USE_FAN
619 if (this->events_.empty())
620 return;
622}
623void WebServer::handle_fan_request(AsyncWebServerRequest *request, const UrlMatch &match) {
624 for (fan::Fan *obj : App.get_fans()) {
625 if (!match.id_equals(obj->get_object_id()))
626 continue;
627
628 if (request->method() == HTTP_GET && match.method_empty()) {
629 auto detail = get_request_detail(request);
630 std::string data = this->fan_json(obj, detail);
631 request->send(200, "application/json", data.c_str());
632 } else if (match.method_equals("toggle")) {
633 this->defer([obj]() { obj->toggle().perform(); });
634 request->send(200);
635 } else if (match.method_equals("turn_on") || match.method_equals("turn_off")) {
636 auto call = match.method_equals("turn_on") ? obj->turn_on() : obj->turn_off();
637
638 parse_int_param_(request, "speed_level", call, &decltype(call)::set_speed);
639
640 if (request->hasParam("oscillation")) {
641 auto speed = request->getParam("oscillation")->value();
642 auto val = parse_on_off(speed.c_str());
643 switch (val) {
644 case PARSE_ON:
645 call.set_oscillating(true);
646 break;
647 case PARSE_OFF:
648 call.set_oscillating(false);
649 break;
650 case PARSE_TOGGLE:
651 call.set_oscillating(!obj->oscillating);
652 break;
653 case PARSE_NONE:
654 request->send(404);
655 return;
656 }
657 }
658 this->defer([call]() mutable { call.perform(); });
659 request->send(200);
660 } else {
661 request->send(404);
662 }
663 return;
664 }
665 request->send(404);
666}
667std::string WebServer::fan_state_json_generator(WebServer *web_server, void *source) {
668 return web_server->fan_json((fan::Fan *) (source), DETAIL_STATE);
669}
670std::string WebServer::fan_all_json_generator(WebServer *web_server, void *source) {
671 return web_server->fan_json((fan::Fan *) (source), DETAIL_ALL);
672}
673std::string WebServer::fan_json(fan::Fan *obj, JsonDetail start_config) {
674 return json::build_json([this, obj, start_config](JsonObject root) {
675 set_json_icon_state_value(root, obj, "fan-" + obj->get_object_id(), obj->state ? "ON" : "OFF", obj->state,
676 start_config);
677 const auto traits = obj->get_traits();
678 if (traits.supports_speed()) {
679 root["speed_level"] = obj->speed;
680 root["speed_count"] = traits.supported_speed_count();
681 }
682 if (obj->get_traits().supports_oscillation())
683 root["oscillation"] = obj->oscillating;
684 if (start_config == DETAIL_ALL) {
685 this->add_sorting_info_(root, obj);
686 }
687 });
688}
689#endif
690
691#ifdef USE_LIGHT
693 if (this->events_.empty())
694 return;
696}
697void WebServer::handle_light_request(AsyncWebServerRequest *request, const UrlMatch &match) {
698 for (light::LightState *obj : App.get_lights()) {
699 if (!match.id_equals(obj->get_object_id()))
700 continue;
701
702 if (request->method() == HTTP_GET && match.method_empty()) {
703 auto detail = get_request_detail(request);
704 std::string data = this->light_json(obj, detail);
705 request->send(200, "application/json", data.c_str());
706 } else if (match.method_equals("toggle")) {
707 this->defer([obj]() { obj->toggle().perform(); });
708 request->send(200);
709 } else if (match.method_equals("turn_on")) {
710 auto call = obj->turn_on();
711
712 // Parse color parameters
713 parse_light_param_(request, "brightness", call, &decltype(call)::set_brightness, 255.0f);
714 parse_light_param_(request, "r", call, &decltype(call)::set_red, 255.0f);
715 parse_light_param_(request, "g", call, &decltype(call)::set_green, 255.0f);
716 parse_light_param_(request, "b", call, &decltype(call)::set_blue, 255.0f);
717 parse_light_param_(request, "white_value", call, &decltype(call)::set_white, 255.0f);
718 parse_light_param_(request, "color_temp", call, &decltype(call)::set_color_temperature);
719
720 // Parse timing parameters
721 parse_light_param_uint_(request, "flash", call, &decltype(call)::set_flash_length, 1000);
722 parse_light_param_uint_(request, "transition", call, &decltype(call)::set_transition_length, 1000);
723
724 parse_string_param_(request, "effect", call, &decltype(call)::set_effect);
725
726 this->defer([call]() mutable { call.perform(); });
727 request->send(200);
728 } else if (match.method_equals("turn_off")) {
729 auto call = obj->turn_off();
730 parse_light_param_uint_(request, "transition", call, &decltype(call)::set_transition_length, 1000);
731 this->defer([call]() mutable { call.perform(); });
732 request->send(200);
733 } else {
734 request->send(404);
735 }
736 return;
737 }
738 request->send(404);
739}
740std::string WebServer::light_state_json_generator(WebServer *web_server, void *source) {
741 return web_server->light_json((light::LightState *) (source), DETAIL_STATE);
742}
743std::string WebServer::light_all_json_generator(WebServer *web_server, void *source) {
744 return web_server->light_json((light::LightState *) (source), DETAIL_ALL);
745}
746std::string WebServer::light_json(light::LightState *obj, JsonDetail start_config) {
747 return json::build_json([this, obj, start_config](JsonObject root) {
748 set_json_id(root, obj, "light-" + obj->get_object_id(), start_config);
749 root["state"] = obj->remote_values.is_on() ? "ON" : "OFF";
750
752 if (start_config == DETAIL_ALL) {
753 JsonArray opt = root["effects"].to<JsonArray>();
754 opt.add("None");
755 for (auto const &option : obj->get_effects()) {
756 opt.add(option->get_name());
757 }
758 this->add_sorting_info_(root, obj);
759 }
760 });
761}
762#endif
763
764#ifdef USE_COVER
766 if (this->events_.empty())
767 return;
769}
770void WebServer::handle_cover_request(AsyncWebServerRequest *request, const UrlMatch &match) {
771 for (cover::Cover *obj : App.get_covers()) {
772 if (!match.id_equals(obj->get_object_id()))
773 continue;
774
775 if (request->method() == HTTP_GET && match.method_empty()) {
776 auto detail = get_request_detail(request);
777 std::string data = this->cover_json(obj, detail);
778 request->send(200, "application/json", data.c_str());
779 return;
780 }
781
782 auto call = obj->make_call();
783 if (match.method_equals("open")) {
784 call.set_command_open();
785 } else if (match.method_equals("close")) {
786 call.set_command_close();
787 } else if (match.method_equals("stop")) {
788 call.set_command_stop();
789 } else if (match.method_equals("toggle")) {
790 call.set_command_toggle();
791 } else if (!match.method_equals("set")) {
792 request->send(404);
793 return;
794 }
795
796 auto traits = obj->get_traits();
797 if ((request->hasParam("position") && !traits.get_supports_position()) ||
798 (request->hasParam("tilt") && !traits.get_supports_tilt())) {
799 request->send(409);
800 return;
801 }
802
803 parse_float_param_(request, "position", call, &decltype(call)::set_position);
804 parse_float_param_(request, "tilt", call, &decltype(call)::set_tilt);
805
806 this->defer([call]() mutable { call.perform(); });
807 request->send(200);
808 return;
809 }
810 request->send(404);
811}
812std::string WebServer::cover_state_json_generator(WebServer *web_server, void *source) {
813 return web_server->cover_json((cover::Cover *) (source), DETAIL_STATE);
814}
815std::string WebServer::cover_all_json_generator(WebServer *web_server, void *source) {
816 return web_server->cover_json((cover::Cover *) (source), DETAIL_STATE);
817}
818std::string WebServer::cover_json(cover::Cover *obj, JsonDetail start_config) {
819 return json::build_json([this, obj, start_config](JsonObject root) {
820 set_json_icon_state_value(root, obj, "cover-" + obj->get_object_id(), obj->is_fully_closed() ? "CLOSED" : "OPEN",
821 obj->position, start_config);
822 root["current_operation"] = cover::cover_operation_to_str(obj->current_operation);
823
825 root["position"] = obj->position;
826 if (obj->get_traits().get_supports_tilt())
827 root["tilt"] = obj->tilt;
828 if (start_config == DETAIL_ALL) {
829 this->add_sorting_info_(root, obj);
830 }
831 });
832}
833#endif
834
835#ifdef USE_NUMBER
837 if (this->events_.empty())
838 return;
840}
841void WebServer::handle_number_request(AsyncWebServerRequest *request, const UrlMatch &match) {
842 for (auto *obj : App.get_numbers()) {
843 if (!match.id_equals(obj->get_object_id()))
844 continue;
845
846 if (request->method() == HTTP_GET && match.method_empty()) {
847 auto detail = get_request_detail(request);
848 std::string data = this->number_json(obj, obj->state, detail);
849 request->send(200, "application/json", data.c_str());
850 return;
851 }
852 if (!match.method_equals("set")) {
853 request->send(404);
854 return;
855 }
856
857 auto call = obj->make_call();
858 parse_float_param_(request, "value", call, &decltype(call)::set_value);
859
860 this->defer([call]() mutable { call.perform(); });
861 request->send(200);
862 return;
863 }
864 request->send(404);
865}
866
867std::string WebServer::number_state_json_generator(WebServer *web_server, void *source) {
868 return web_server->number_json((number::Number *) (source), ((number::Number *) (source))->state, DETAIL_STATE);
869}
870std::string WebServer::number_all_json_generator(WebServer *web_server, void *source) {
871 return web_server->number_json((number::Number *) (source), ((number::Number *) (source))->state, DETAIL_ALL);
872}
873std::string WebServer::number_json(number::Number *obj, float value, JsonDetail start_config) {
874 return json::build_json([this, obj, value, start_config](JsonObject root) {
875 set_json_id(root, obj, "number-" + obj->get_object_id(), start_config);
876 if (start_config == DETAIL_ALL) {
877 root["min_value"] =
879 root["max_value"] =
881 root["step"] =
883 root["mode"] = (int) obj->traits.get_mode();
884 if (!obj->traits.get_unit_of_measurement().empty())
885 root["uom"] = obj->traits.get_unit_of_measurement();
886 this->add_sorting_info_(root, obj);
887 }
888 if (std::isnan(value)) {
889 root["value"] = "\"NaN\"";
890 root["state"] = "NA";
891 } else {
894 if (!obj->traits.get_unit_of_measurement().empty())
895 state += " " + obj->traits.get_unit_of_measurement();
896 root["state"] = state;
897 }
898 });
899}
900#endif
901
902#ifdef USE_DATETIME_DATE
904 if (this->events_.empty())
905 return;
907}
908void WebServer::handle_date_request(AsyncWebServerRequest *request, const UrlMatch &match) {
909 for (auto *obj : App.get_dates()) {
910 if (!match.id_equals(obj->get_object_id()))
911 continue;
912 if (request->method() == HTTP_GET && match.method_empty()) {
913 auto detail = get_request_detail(request);
914 std::string data = this->date_json(obj, detail);
915 request->send(200, "application/json", data.c_str());
916 return;
917 }
918 if (!match.method_equals("set")) {
919 request->send(404);
920 return;
921 }
922
923 auto call = obj->make_call();
924
925 if (!request->hasParam("value")) {
926 request->send(409);
927 return;
928 }
929
930 parse_string_param_(request, "value", call, &decltype(call)::set_date);
931
932 this->defer([call]() mutable { call.perform(); });
933 request->send(200);
934 return;
935 }
936 request->send(404);
937}
938
939std::string WebServer::date_state_json_generator(WebServer *web_server, void *source) {
940 return web_server->date_json((datetime::DateEntity *) (source), DETAIL_STATE);
941}
942std::string WebServer::date_all_json_generator(WebServer *web_server, void *source) {
943 return web_server->date_json((datetime::DateEntity *) (source), DETAIL_ALL);
944}
945std::string WebServer::date_json(datetime::DateEntity *obj, JsonDetail start_config) {
946 return json::build_json([this, obj, start_config](JsonObject root) {
947 set_json_id(root, obj, "date-" + obj->get_object_id(), start_config);
948 std::string value = str_sprintf("%d-%02d-%02d", obj->year, obj->month, obj->day);
949 root["value"] = value;
950 root["state"] = value;
951 if (start_config == DETAIL_ALL) {
952 this->add_sorting_info_(root, obj);
953 }
954 });
955}
956#endif // USE_DATETIME_DATE
957
958#ifdef USE_DATETIME_TIME
960 if (this->events_.empty())
961 return;
963}
964void WebServer::handle_time_request(AsyncWebServerRequest *request, const UrlMatch &match) {
965 for (auto *obj : App.get_times()) {
966 if (!match.id_equals(obj->get_object_id()))
967 continue;
968 if (request->method() == HTTP_GET && match.method_empty()) {
969 auto detail = get_request_detail(request);
970 std::string data = this->time_json(obj, detail);
971 request->send(200, "application/json", data.c_str());
972 return;
973 }
974 if (!match.method_equals("set")) {
975 request->send(404);
976 return;
977 }
978
979 auto call = obj->make_call();
980
981 if (!request->hasParam("value")) {
982 request->send(409);
983 return;
984 }
985
986 parse_string_param_(request, "value", call, &decltype(call)::set_time);
987
988 this->defer([call]() mutable { call.perform(); });
989 request->send(200);
990 return;
991 }
992 request->send(404);
993}
994std::string WebServer::time_state_json_generator(WebServer *web_server, void *source) {
995 return web_server->time_json((datetime::TimeEntity *) (source), DETAIL_STATE);
996}
997std::string WebServer::time_all_json_generator(WebServer *web_server, void *source) {
998 return web_server->time_json((datetime::TimeEntity *) (source), DETAIL_ALL);
999}
1001 return json::build_json([this, obj, start_config](JsonObject root) {
1002 set_json_id(root, obj, "time-" + obj->get_object_id(), start_config);
1003 std::string value = str_sprintf("%02d:%02d:%02d", obj->hour, obj->minute, obj->second);
1004 root["value"] = value;
1005 root["state"] = value;
1006 if (start_config == DETAIL_ALL) {
1007 this->add_sorting_info_(root, obj);
1008 }
1009 });
1010}
1011#endif // USE_DATETIME_TIME
1012
1013#ifdef USE_DATETIME_DATETIME
1015 if (this->events_.empty())
1016 return;
1018}
1019void WebServer::handle_datetime_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1020 for (auto *obj : App.get_datetimes()) {
1021 if (!match.id_equals(obj->get_object_id()))
1022 continue;
1023 if (request->method() == HTTP_GET && match.method_empty()) {
1024 auto detail = get_request_detail(request);
1025 std::string data = this->datetime_json(obj, detail);
1026 request->send(200, "application/json", data.c_str());
1027 return;
1028 }
1029 if (!match.method_equals("set")) {
1030 request->send(404);
1031 return;
1032 }
1033
1034 auto call = obj->make_call();
1035
1036 if (!request->hasParam("value")) {
1037 request->send(409);
1038 return;
1039 }
1040
1041 parse_string_param_(request, "value", call, &decltype(call)::set_datetime);
1042
1043 this->defer([call]() mutable { call.perform(); });
1044 request->send(200);
1045 return;
1046 }
1047 request->send(404);
1048}
1049std::string WebServer::datetime_state_json_generator(WebServer *web_server, void *source) {
1050 return web_server->datetime_json((datetime::DateTimeEntity *) (source), DETAIL_STATE);
1051}
1052std::string WebServer::datetime_all_json_generator(WebServer *web_server, void *source) {
1053 return web_server->datetime_json((datetime::DateTimeEntity *) (source), DETAIL_ALL);
1054}
1056 return json::build_json([this, obj, start_config](JsonObject root) {
1057 set_json_id(root, obj, "datetime-" + obj->get_object_id(), start_config);
1058 std::string value = str_sprintf("%d-%02d-%02d %02d:%02d:%02d", obj->year, obj->month, obj->day, obj->hour,
1059 obj->minute, obj->second);
1060 root["value"] = value;
1061 root["state"] = value;
1062 if (start_config == DETAIL_ALL) {
1063 this->add_sorting_info_(root, obj);
1064 }
1065 });
1066}
1067#endif // USE_DATETIME_DATETIME
1068
1069#ifdef USE_TEXT
1070void WebServer::on_text_update(text::Text *obj, const std::string &state) {
1071 if (this->events_.empty())
1072 return;
1074}
1075void WebServer::handle_text_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1076 for (auto *obj : App.get_texts()) {
1077 if (!match.id_equals(obj->get_object_id()))
1078 continue;
1079
1080 if (request->method() == HTTP_GET && match.method_empty()) {
1081 auto detail = get_request_detail(request);
1082 std::string data = this->text_json(obj, obj->state, detail);
1083 request->send(200, "application/json", data.c_str());
1084 return;
1085 }
1086 if (!match.method_equals("set")) {
1087 request->send(404);
1088 return;
1089 }
1090
1091 auto call = obj->make_call();
1092 parse_string_param_(request, "value", call, &decltype(call)::set_value);
1093
1094 this->defer([call]() mutable { call.perform(); });
1095 request->send(200);
1096 return;
1097 }
1098 request->send(404);
1099}
1100
1101std::string WebServer::text_state_json_generator(WebServer *web_server, void *source) {
1102 return web_server->text_json((text::Text *) (source), ((text::Text *) (source))->state, DETAIL_STATE);
1103}
1104std::string WebServer::text_all_json_generator(WebServer *web_server, void *source) {
1105 return web_server->text_json((text::Text *) (source), ((text::Text *) (source))->state, DETAIL_ALL);
1106}
1107std::string WebServer::text_json(text::Text *obj, const std::string &value, JsonDetail start_config) {
1108 return json::build_json([this, obj, value, start_config](JsonObject root) {
1109 set_json_id(root, obj, "text-" + obj->get_object_id(), start_config);
1110 root["min_length"] = obj->traits.get_min_length();
1111 root["max_length"] = obj->traits.get_max_length();
1112 root["pattern"] = obj->traits.get_pattern();
1114 root["state"] = "********";
1115 } else {
1116 root["state"] = value;
1117 }
1118 root["value"] = value;
1119 if (start_config == DETAIL_ALL) {
1120 root["mode"] = (int) obj->traits.get_mode();
1121 this->add_sorting_info_(root, obj);
1122 }
1123 });
1124}
1125#endif
1126
1127#ifdef USE_SELECT
1128void WebServer::on_select_update(select::Select *obj, const std::string &state, size_t index) {
1129 if (this->events_.empty())
1130 return;
1132}
1133void WebServer::handle_select_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1134 for (auto *obj : App.get_selects()) {
1135 if (!match.id_equals(obj->get_object_id()))
1136 continue;
1137
1138 if (request->method() == HTTP_GET && match.method_empty()) {
1139 auto detail = get_request_detail(request);
1140 std::string data = this->select_json(obj, obj->state, detail);
1141 request->send(200, "application/json", data.c_str());
1142 return;
1143 }
1144
1145 if (!match.method_equals("set")) {
1146 request->send(404);
1147 return;
1148 }
1149
1150 auto call = obj->make_call();
1151 parse_string_param_(request, "option", call, &decltype(call)::set_option);
1152
1153 this->defer([call]() mutable { call.perform(); });
1154 request->send(200);
1155 return;
1156 }
1157 request->send(404);
1158}
1159std::string WebServer::select_state_json_generator(WebServer *web_server, void *source) {
1160 return web_server->select_json((select::Select *) (source), ((select::Select *) (source))->state, DETAIL_STATE);
1161}
1162std::string WebServer::select_all_json_generator(WebServer *web_server, void *source) {
1163 return web_server->select_json((select::Select *) (source), ((select::Select *) (source))->state, DETAIL_ALL);
1164}
1165std::string WebServer::select_json(select::Select *obj, const std::string &value, JsonDetail start_config) {
1166 return json::build_json([this, obj, value, start_config](JsonObject root) {
1167 set_json_icon_state_value(root, obj, "select-" + obj->get_object_id(), value, value, start_config);
1168 if (start_config == DETAIL_ALL) {
1169 JsonArray opt = root["option"].to<JsonArray>();
1170 for (auto &option : obj->traits.get_options()) {
1171 opt.add(option);
1172 }
1173 this->add_sorting_info_(root, obj);
1174 }
1175 });
1176}
1177#endif
1178
1179// Longest: HORIZONTAL
1180#define PSTR_LOCAL(mode_s) strncpy_P(buf, (PGM_P) ((mode_s)), 15)
1181
1182#ifdef USE_CLIMATE
1184 if (this->events_.empty())
1185 return;
1187}
1188void WebServer::handle_climate_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1189 for (auto *obj : App.get_climates()) {
1190 if (!match.id_equals(obj->get_object_id()))
1191 continue;
1192
1193 if (request->method() == HTTP_GET && match.method_empty()) {
1194 auto detail = get_request_detail(request);
1195 std::string data = this->climate_json(obj, detail);
1196 request->send(200, "application/json", data.c_str());
1197 return;
1198 }
1199
1200 if (!match.method_equals("set")) {
1201 request->send(404);
1202 return;
1203 }
1204
1205 auto call = obj->make_call();
1206
1207 // Parse string mode parameters
1208 parse_string_param_(request, "mode", call, &decltype(call)::set_mode);
1209 parse_string_param_(request, "fan_mode", call, &decltype(call)::set_fan_mode);
1210 parse_string_param_(request, "swing_mode", call, &decltype(call)::set_swing_mode);
1211
1212 // Parse temperature parameters
1213 parse_float_param_(request, "target_temperature_high", call, &decltype(call)::set_target_temperature_high);
1214 parse_float_param_(request, "target_temperature_low", call, &decltype(call)::set_target_temperature_low);
1215 parse_float_param_(request, "target_temperature", call, &decltype(call)::set_target_temperature);
1216
1217 this->defer([call]() mutable { call.perform(); });
1218 request->send(200);
1219 return;
1220 }
1221 request->send(404);
1222}
1223std::string WebServer::climate_state_json_generator(WebServer *web_server, void *source) {
1224 return web_server->climate_json((climate::Climate *) (source), DETAIL_STATE);
1225}
1226std::string WebServer::climate_all_json_generator(WebServer *web_server, void *source) {
1227 return web_server->climate_json((climate::Climate *) (source), DETAIL_ALL);
1228}
1229std::string WebServer::climate_json(climate::Climate *obj, JsonDetail start_config) {
1230 // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
1231 return json::build_json([this, obj, start_config](JsonObject root) {
1232 set_json_id(root, obj, "climate-" + obj->get_object_id(), start_config);
1233 const auto traits = obj->get_traits();
1234 int8_t target_accuracy = traits.get_target_temperature_accuracy_decimals();
1235 int8_t current_accuracy = traits.get_current_temperature_accuracy_decimals();
1236 char buf[16];
1237
1238 if (start_config == DETAIL_ALL) {
1239 JsonArray opt = root["modes"].to<JsonArray>();
1240 for (climate::ClimateMode m : traits.get_supported_modes())
1241 opt.add(PSTR_LOCAL(climate::climate_mode_to_string(m)));
1242 if (!traits.get_supported_custom_fan_modes().empty()) {
1243 JsonArray opt = root["fan_modes"].to<JsonArray>();
1244 for (climate::ClimateFanMode m : traits.get_supported_fan_modes())
1245 opt.add(PSTR_LOCAL(climate::climate_fan_mode_to_string(m)));
1246 }
1247
1248 if (!traits.get_supported_custom_fan_modes().empty()) {
1249 JsonArray opt = root["custom_fan_modes"].to<JsonArray>();
1250 for (auto const &custom_fan_mode : traits.get_supported_custom_fan_modes())
1251 opt.add(custom_fan_mode);
1252 }
1253 if (traits.get_supports_swing_modes()) {
1254 JsonArray opt = root["swing_modes"].to<JsonArray>();
1255 for (auto swing_mode : traits.get_supported_swing_modes())
1257 }
1258 if (traits.get_supports_presets() && obj->preset.has_value()) {
1259 JsonArray opt = root["presets"].to<JsonArray>();
1260 for (climate::ClimatePreset m : traits.get_supported_presets())
1261 opt.add(PSTR_LOCAL(climate::climate_preset_to_string(m)));
1262 }
1263 if (!traits.get_supported_custom_presets().empty() && obj->custom_preset.has_value()) {
1264 JsonArray opt = root["custom_presets"].to<JsonArray>();
1265 for (auto const &custom_preset : traits.get_supported_custom_presets())
1266 opt.add(custom_preset);
1267 }
1268 this->add_sorting_info_(root, obj);
1269 }
1270
1271 bool has_state = false;
1272 root["mode"] = PSTR_LOCAL(climate_mode_to_string(obj->mode));
1273 root["max_temp"] = value_accuracy_to_string(traits.get_visual_max_temperature(), target_accuracy);
1274 root["min_temp"] = value_accuracy_to_string(traits.get_visual_min_temperature(), target_accuracy);
1275 root["step"] = traits.get_visual_target_temperature_step();
1276 if (traits.get_supports_action()) {
1277 root["action"] = PSTR_LOCAL(climate_action_to_string(obj->action));
1278 root["state"] = root["action"];
1279 has_state = true;
1280 }
1281 if (traits.get_supports_fan_modes() && obj->fan_mode.has_value()) {
1282 root["fan_mode"] = PSTR_LOCAL(climate_fan_mode_to_string(obj->fan_mode.value()));
1283 }
1284 if (!traits.get_supported_custom_fan_modes().empty() && obj->custom_fan_mode.has_value()) {
1285 root["custom_fan_mode"] = obj->custom_fan_mode.value().c_str();
1286 }
1287 if (traits.get_supports_presets() && obj->preset.has_value()) {
1288 root["preset"] = PSTR_LOCAL(climate_preset_to_string(obj->preset.value()));
1289 }
1290 if (!traits.get_supported_custom_presets().empty() && obj->custom_preset.has_value()) {
1291 root["custom_preset"] = obj->custom_preset.value().c_str();
1292 }
1293 if (traits.get_supports_swing_modes()) {
1294 root["swing_mode"] = PSTR_LOCAL(climate_swing_mode_to_string(obj->swing_mode));
1295 }
1296 if (traits.get_supports_current_temperature()) {
1297 if (!std::isnan(obj->current_temperature)) {
1298 root["current_temperature"] = value_accuracy_to_string(obj->current_temperature, current_accuracy);
1299 } else {
1300 root["current_temperature"] = "NA";
1301 }
1302 }
1303 if (traits.get_supports_two_point_target_temperature()) {
1304 root["target_temperature_low"] = value_accuracy_to_string(obj->target_temperature_low, target_accuracy);
1305 root["target_temperature_high"] = value_accuracy_to_string(obj->target_temperature_high, target_accuracy);
1306 if (!has_state) {
1307 root["state"] = value_accuracy_to_string((obj->target_temperature_high + obj->target_temperature_low) / 2.0f,
1308 target_accuracy);
1309 }
1310 } else {
1311 root["target_temperature"] = value_accuracy_to_string(obj->target_temperature, target_accuracy);
1312 if (!has_state)
1313 root["state"] = root["target_temperature"];
1314 }
1315 });
1316 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
1317}
1318#endif
1319
1320#ifdef USE_LOCK
1322 if (this->events_.empty())
1323 return;
1325}
1326void WebServer::handle_lock_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1327 for (lock::Lock *obj : App.get_locks()) {
1328 if (!match.id_equals(obj->get_object_id()))
1329 continue;
1330
1331 if (request->method() == HTTP_GET && match.method_empty()) {
1332 auto detail = get_request_detail(request);
1333 std::string data = this->lock_json(obj, obj->state, detail);
1334 request->send(200, "application/json", data.c_str());
1335 } else if (match.method_equals("lock")) {
1336 this->defer([obj]() { obj->lock(); });
1337 request->send(200);
1338 } else if (match.method_equals("unlock")) {
1339 this->defer([obj]() { obj->unlock(); });
1340 request->send(200);
1341 } else if (match.method_equals("open")) {
1342 this->defer([obj]() { obj->open(); });
1343 request->send(200);
1344 } else {
1345 request->send(404);
1346 }
1347 return;
1348 }
1349 request->send(404);
1350}
1351std::string WebServer::lock_state_json_generator(WebServer *web_server, void *source) {
1352 return web_server->lock_json((lock::Lock *) (source), ((lock::Lock *) (source))->state, DETAIL_STATE);
1353}
1354std::string WebServer::lock_all_json_generator(WebServer *web_server, void *source) {
1355 return web_server->lock_json((lock::Lock *) (source), ((lock::Lock *) (source))->state, DETAIL_ALL);
1356}
1357std::string WebServer::lock_json(lock::Lock *obj, lock::LockState value, JsonDetail start_config) {
1358 return json::build_json([this, obj, value, start_config](JsonObject root) {
1359 set_json_icon_state_value(root, obj, "lock-" + obj->get_object_id(), lock::lock_state_to_string(value), value,
1360 start_config);
1361 if (start_config == DETAIL_ALL) {
1362 this->add_sorting_info_(root, obj);
1363 }
1364 });
1365}
1366#endif
1367
1368#ifdef USE_VALVE
1370 if (this->events_.empty())
1371 return;
1373}
1374void WebServer::handle_valve_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1375 for (valve::Valve *obj : App.get_valves()) {
1376 if (!match.id_equals(obj->get_object_id()))
1377 continue;
1378
1379 if (request->method() == HTTP_GET && match.method_empty()) {
1380 auto detail = get_request_detail(request);
1381 std::string data = this->valve_json(obj, detail);
1382 request->send(200, "application/json", data.c_str());
1383 return;
1384 }
1385
1386 auto call = obj->make_call();
1387 if (match.method_equals("open")) {
1388 call.set_command_open();
1389 } else if (match.method_equals("close")) {
1390 call.set_command_close();
1391 } else if (match.method_equals("stop")) {
1392 call.set_command_stop();
1393 } else if (match.method_equals("toggle")) {
1394 call.set_command_toggle();
1395 } else if (!match.method_equals("set")) {
1396 request->send(404);
1397 return;
1398 }
1399
1400 auto traits = obj->get_traits();
1401 if (request->hasParam("position") && !traits.get_supports_position()) {
1402 request->send(409);
1403 return;
1404 }
1405
1406 parse_float_param_(request, "position", call, &decltype(call)::set_position);
1407
1408 this->defer([call]() mutable { call.perform(); });
1409 request->send(200);
1410 return;
1411 }
1412 request->send(404);
1413}
1414std::string WebServer::valve_state_json_generator(WebServer *web_server, void *source) {
1415 return web_server->valve_json((valve::Valve *) (source), DETAIL_STATE);
1416}
1417std::string WebServer::valve_all_json_generator(WebServer *web_server, void *source) {
1418 return web_server->valve_json((valve::Valve *) (source), DETAIL_ALL);
1419}
1420std::string WebServer::valve_json(valve::Valve *obj, JsonDetail start_config) {
1421 return json::build_json([this, obj, start_config](JsonObject root) {
1422 set_json_icon_state_value(root, obj, "valve-" + obj->get_object_id(), obj->is_fully_closed() ? "CLOSED" : "OPEN",
1423 obj->position, start_config);
1424 root["current_operation"] = valve::valve_operation_to_str(obj->current_operation);
1425
1426 if (obj->get_traits().get_supports_position())
1427 root["position"] = obj->position;
1428 if (start_config == DETAIL_ALL) {
1429 this->add_sorting_info_(root, obj);
1430 }
1431 });
1432}
1433#endif
1434
1435#ifdef USE_ALARM_CONTROL_PANEL
1441void WebServer::handle_alarm_control_panel_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1442 for (alarm_control_panel::AlarmControlPanel *obj : App.get_alarm_control_panels()) {
1443 if (!match.id_equals(obj->get_object_id()))
1444 continue;
1445
1446 if (request->method() == HTTP_GET && match.method_empty()) {
1447 auto detail = get_request_detail(request);
1448 std::string data = this->alarm_control_panel_json(obj, obj->get_state(), detail);
1449 request->send(200, "application/json", data.c_str());
1450 return;
1451 }
1452
1453 auto call = obj->make_call();
1454 parse_string_param_(request, "code", call, &decltype(call)::set_code);
1455
1456 if (match.method_equals("disarm")) {
1457 call.disarm();
1458 } else if (match.method_equals("arm_away")) {
1459 call.arm_away();
1460 } else if (match.method_equals("arm_home")) {
1461 call.arm_home();
1462 } else if (match.method_equals("arm_night")) {
1463 call.arm_night();
1464 } else if (match.method_equals("arm_vacation")) {
1465 call.arm_vacation();
1466 } else {
1467 request->send(404);
1468 return;
1469 }
1470
1471 this->defer([call]() mutable { call.perform(); });
1472 request->send(200);
1473 return;
1474 }
1475 request->send(404);
1476}
1479 ((alarm_control_panel::AlarmControlPanel *) (source))->get_state(),
1480 DETAIL_STATE);
1481}
1482std::string WebServer::alarm_control_panel_all_json_generator(WebServer *web_server, void *source) {
1484 ((alarm_control_panel::AlarmControlPanel *) (source))->get_state(),
1485 DETAIL_ALL);
1486}
1489 JsonDetail start_config) {
1490 return json::build_json([this, obj, value, start_config](JsonObject root) {
1491 char buf[16];
1492 set_json_icon_state_value(root, obj, "alarm-control-panel-" + obj->get_object_id(),
1493 PSTR_LOCAL(alarm_control_panel_state_to_string(value)), value, start_config);
1494 if (start_config == DETAIL_ALL) {
1495 this->add_sorting_info_(root, obj);
1496 }
1497 });
1498}
1499#endif
1500
1501#ifdef USE_EVENT
1502void WebServer::on_event(event::Event *obj, const std::string &event_type) {
1504}
1505
1506void WebServer::handle_event_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1507 for (event::Event *obj : App.get_events()) {
1508 if (!match.id_equals(obj->get_object_id()))
1509 continue;
1510
1511 if (request->method() == HTTP_GET && match.method_empty()) {
1512 auto detail = get_request_detail(request);
1513 std::string data = this->event_json(obj, "", detail);
1514 request->send(200, "application/json", data.c_str());
1515 return;
1516 }
1517 }
1518 request->send(404);
1519}
1520
1521static std::string get_event_type(event::Event *event) {
1522 return (event && event->last_event_type) ? *event->last_event_type : "";
1523}
1524
1525std::string WebServer::event_state_json_generator(WebServer *web_server, void *source) {
1526 auto *event = static_cast<event::Event *>(source);
1527 return web_server->event_json(event, get_event_type(event), DETAIL_STATE);
1528}
1529std::string WebServer::event_all_json_generator(WebServer *web_server, void *source) {
1530 auto *event = static_cast<event::Event *>(source);
1531 return web_server->event_json(event, get_event_type(event), DETAIL_ALL);
1532}
1533std::string WebServer::event_json(event::Event *obj, const std::string &event_type, JsonDetail start_config) {
1534 return json::build_json([this, obj, event_type, start_config](JsonObject root) {
1535 set_json_id(root, obj, "event-" + obj->get_object_id(), start_config);
1536 if (!event_type.empty()) {
1537 root["event_type"] = event_type;
1538 }
1539 if (start_config == DETAIL_ALL) {
1540 JsonArray event_types = root["event_types"].to<JsonArray>();
1541 for (auto const &event_type : obj->get_event_types()) {
1542 event_types.add(event_type);
1543 }
1544 root["device_class"] = obj->get_device_class();
1545 this->add_sorting_info_(root, obj);
1546 }
1547 });
1548}
1549#endif
1550
1551#ifdef USE_UPDATE
1552static const char *update_state_to_string(update::UpdateState state) {
1553 switch (state) {
1555 return "NO UPDATE";
1557 return "UPDATE AVAILABLE";
1559 return "INSTALLING";
1560 default:
1561 return "UNKNOWN";
1562 }
1563}
1564
1566 if (this->events_.empty())
1567 return;
1569}
1570void WebServer::handle_update_request(AsyncWebServerRequest *request, const UrlMatch &match) {
1571 for (update::UpdateEntity *obj : App.get_updates()) {
1572 if (!match.id_equals(obj->get_object_id()))
1573 continue;
1574
1575 if (request->method() == HTTP_GET && match.method_empty()) {
1576 auto detail = get_request_detail(request);
1577 std::string data = this->update_json(obj, detail);
1578 request->send(200, "application/json", data.c_str());
1579 return;
1580 }
1581
1582 if (!match.method_equals("install")) {
1583 request->send(404);
1584 return;
1585 }
1586
1587 this->defer([obj]() mutable { obj->perform(); });
1588 request->send(200);
1589 return;
1590 }
1591 request->send(404);
1592}
1593std::string WebServer::update_state_json_generator(WebServer *web_server, void *source) {
1594 return web_server->update_json((update::UpdateEntity *) (source), DETAIL_STATE);
1595}
1596std::string WebServer::update_all_json_generator(WebServer *web_server, void *source) {
1597 return web_server->update_json((update::UpdateEntity *) (source), DETAIL_STATE);
1598}
1600 // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
1601 return json::build_json([this, obj, start_config](JsonObject root) {
1602 set_json_id(root, obj, "update-" + obj->get_object_id(), start_config);
1603 root["value"] = obj->update_info.latest_version;
1604 root["state"] = update_state_to_string(obj->state);
1605 if (start_config == DETAIL_ALL) {
1606 root["current_version"] = obj->update_info.current_version;
1607 root["title"] = obj->update_info.title;
1608 root["summary"] = obj->update_info.summary;
1609 root["release_url"] = obj->update_info.release_url;
1610 this->add_sorting_info_(root, obj);
1611 }
1612 });
1613 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
1614}
1615#endif
1616
1617bool WebServer::canHandle(AsyncWebServerRequest *request) const {
1618 const auto &url = request->url();
1619 const auto method = request->method();
1620
1621 // Simple URL checks
1622 if (url == "/")
1623 return true;
1624
1625#ifdef USE_ARDUINO
1626 if (url == "/events")
1627 return true;
1628#endif
1629
1630#ifdef USE_WEBSERVER_CSS_INCLUDE
1631 if (url == "/0.css")
1632 return true;
1633#endif
1634
1635#ifdef USE_WEBSERVER_JS_INCLUDE
1636 if (url == "/0.js")
1637 return true;
1638#endif
1639
1640#ifdef USE_WEBSERVER_PRIVATE_NETWORK_ACCESS
1641 if (method == HTTP_OPTIONS && request->hasHeader(HEADER_CORS_REQ_PNA))
1642 return true;
1643#endif
1644
1645 // Parse URL for component checks
1646 UrlMatch match = match_url(url.c_str(), url.length(), true);
1647 if (!match.valid)
1648 return false;
1649
1650 // Common pattern check
1651 bool is_get = method == HTTP_GET;
1652 bool is_post = method == HTTP_POST;
1653 bool is_get_or_post = is_get || is_post;
1654
1655 if (!is_get_or_post)
1656 return false;
1657
1658 // GET-only components
1659 if (is_get) {
1660#ifdef USE_SENSOR
1661 if (match.domain_equals("sensor"))
1662 return true;
1663#endif
1664#ifdef USE_BINARY_SENSOR
1665 if (match.domain_equals("binary_sensor"))
1666 return true;
1667#endif
1668#ifdef USE_TEXT_SENSOR
1669 if (match.domain_equals("text_sensor"))
1670 return true;
1671#endif
1672#ifdef USE_EVENT
1673 if (match.domain_equals("event"))
1674 return true;
1675#endif
1676 }
1677
1678 // GET+POST components
1679 if (is_get_or_post) {
1680#ifdef USE_SWITCH
1681 if (match.domain_equals("switch"))
1682 return true;
1683#endif
1684#ifdef USE_BUTTON
1685 if (match.domain_equals("button"))
1686 return true;
1687#endif
1688#ifdef USE_FAN
1689 if (match.domain_equals("fan"))
1690 return true;
1691#endif
1692#ifdef USE_LIGHT
1693 if (match.domain_equals("light"))
1694 return true;
1695#endif
1696#ifdef USE_COVER
1697 if (match.domain_equals("cover"))
1698 return true;
1699#endif
1700#ifdef USE_NUMBER
1701 if (match.domain_equals("number"))
1702 return true;
1703#endif
1704#ifdef USE_DATETIME_DATE
1705 if (match.domain_equals("date"))
1706 return true;
1707#endif
1708#ifdef USE_DATETIME_TIME
1709 if (match.domain_equals("time"))
1710 return true;
1711#endif
1712#ifdef USE_DATETIME_DATETIME
1713 if (match.domain_equals("datetime"))
1714 return true;
1715#endif
1716#ifdef USE_TEXT
1717 if (match.domain_equals("text"))
1718 return true;
1719#endif
1720#ifdef USE_SELECT
1721 if (match.domain_equals("select"))
1722 return true;
1723#endif
1724#ifdef USE_CLIMATE
1725 if (match.domain_equals("climate"))
1726 return true;
1727#endif
1728#ifdef USE_LOCK
1729 if (match.domain_equals("lock"))
1730 return true;
1731#endif
1732#ifdef USE_VALVE
1733 if (match.domain_equals("valve"))
1734 return true;
1735#endif
1736#ifdef USE_ALARM_CONTROL_PANEL
1737 if (match.domain_equals("alarm_control_panel"))
1738 return true;
1739#endif
1740#ifdef USE_UPDATE
1741 if (match.domain_equals("update"))
1742 return true;
1743#endif
1744 }
1745
1746 return false;
1747}
1748void WebServer::handleRequest(AsyncWebServerRequest *request) {
1749 const auto &url = request->url();
1750
1751 // Handle static routes first
1752 if (url == "/") {
1753 this->handle_index_request(request);
1754 return;
1755 }
1756
1757#ifdef USE_ARDUINO
1758 if (url == "/events") {
1759 this->events_.add_new_client(this, request);
1760 return;
1761 }
1762#endif
1763
1764#ifdef USE_WEBSERVER_CSS_INCLUDE
1765 if (url == "/0.css") {
1766 this->handle_css_request(request);
1767 return;
1768 }
1769#endif
1770
1771#ifdef USE_WEBSERVER_JS_INCLUDE
1772 if (url == "/0.js") {
1773 this->handle_js_request(request);
1774 return;
1775 }
1776#endif
1777
1778#ifdef USE_WEBSERVER_PRIVATE_NETWORK_ACCESS
1779 if (request->method() == HTTP_OPTIONS && request->hasHeader(HEADER_CORS_REQ_PNA)) {
1780 this->handle_pna_cors_request(request);
1781 return;
1782 }
1783#endif
1784
1785 // Parse URL for component routing
1786 UrlMatch match = match_url(url.c_str(), url.length(), false);
1787
1788 // Component routing using minimal code repetition
1789 struct ComponentRoute {
1790 const char *domain;
1791 void (WebServer::*handler)(AsyncWebServerRequest *, const UrlMatch &);
1792 };
1793
1794 static const ComponentRoute ROUTES[] = {
1795#ifdef USE_SENSOR
1797#endif
1798#ifdef USE_SWITCH
1800#endif
1801#ifdef USE_BUTTON
1803#endif
1804#ifdef USE_BINARY_SENSOR
1805 {"binary_sensor", &WebServer::handle_binary_sensor_request},
1806#endif
1807#ifdef USE_FAN
1809#endif
1810#ifdef USE_LIGHT
1812#endif
1813#ifdef USE_TEXT_SENSOR
1814 {"text_sensor", &WebServer::handle_text_sensor_request},
1815#endif
1816#ifdef USE_COVER
1818#endif
1819#ifdef USE_NUMBER
1821#endif
1822#ifdef USE_DATETIME_DATE
1824#endif
1825#ifdef USE_DATETIME_TIME
1827#endif
1828#ifdef USE_DATETIME_DATETIME
1830#endif
1831#ifdef USE_TEXT
1833#endif
1834#ifdef USE_SELECT
1836#endif
1837#ifdef USE_CLIMATE
1839#endif
1840#ifdef USE_LOCK
1842#endif
1843#ifdef USE_VALVE
1845#endif
1846#ifdef USE_ALARM_CONTROL_PANEL
1847 {"alarm_control_panel", &WebServer::handle_alarm_control_panel_request},
1848#endif
1849#ifdef USE_UPDATE
1851#endif
1852 };
1853
1854 // Check each route
1855 for (const auto &route : ROUTES) {
1856 if (match.domain_equals(route.domain)) {
1857 (this->*route.handler)(request, match);
1858 return;
1859 }
1860 }
1861
1862 // No matching handler found - send 404
1863 ESP_LOGV(TAG, "Request for unknown URL: %s", url.c_str());
1864 request->send(404, "text/plain", "Not Found");
1865}
1866
1867bool WebServer::isRequestHandlerTrivial() const { return false; }
1868
1869void WebServer::add_sorting_info_(JsonObject &root, EntityBase *entity) {
1870#ifdef USE_WEBSERVER_SORTING
1871 if (this->sorting_entitys_.find(entity) != this->sorting_entitys_.end()) {
1872 root["sorting_weight"] = this->sorting_entitys_[entity].weight;
1873 if (this->sorting_groups_.find(this->sorting_entitys_[entity].group_id) != this->sorting_groups_.end()) {
1874 root["sorting_group"] = this->sorting_groups_[this->sorting_entitys_[entity].group_id].name;
1875 }
1876 }
1877#endif
1878}
1879
1880#ifdef USE_WEBSERVER_SORTING
1881void WebServer::add_entity_config(EntityBase *entity, float weight, uint64_t group) {
1882 this->sorting_entitys_[entity] = SortingComponents{weight, group};
1883}
1884
1885void WebServer::add_sorting_group(uint64_t group_id, const std::string &group_name, float weight) {
1886 this->sorting_groups_[group_id] = SortingGroup{group_name, weight};
1887}
1888#endif
1889
1890} // namespace web_server
1891} // namespace esphome
1892#endif
uint8_t m
Definition bl0906.h:1
std::string get_comment() const
Get the comment of this Application set by pre_setup().
const std::string & get_friendly_name() const
Get the friendly name of this Application set by pre_setup().
const std::string & get_name() const
Get the name of this Application set by pre_setup().
auto & get_binary_sensors() const
void set_interval(const std::string &name, uint32_t interval, std::function< void()> &&f)
Set an interval function with a unique name.
Definition component.cpp:89
void defer(const std::string &name, std::function< void()> &&f)
Defer a callback to the next loop() call.
void begin(bool include_internal=false)
void setup_controller(bool include_internal=false)
Definition controller.cpp:7
std::string get_device_class()
Get the device class, using the manual override if set.
std::string get_unit_of_measurement()
Get the unit of measurement, using the manual override if set.
const StringRef & get_name() const
std::string get_icon() const
bool is_disabled_by_default() const
Definition entity_base.h:45
std::string get_object_id() const
EntityCategory get_entity_category() const
Definition entity_base.h:49
Base class for all binary_sensor-type classes.
Base class for all buttons.
Definition button.h:29
ClimateDevice - This is the base class for all climate integrations.
Definition climate.h:168
ClimateMode mode
The active mode of the climate device.
Definition climate.h:173
optional< ClimateFanMode > fan_mode
The active fan mode of the climate device.
Definition climate.h:199
ClimateTraits get_traits()
Get the traits of this climate device with all overrides applied.
Definition climate.cpp:440
float target_temperature
The target temperature of the climate device.
Definition climate.h:186
optional< std::string > custom_fan_mode
The active custom fan mode of the climate device.
Definition climate.h:205
ClimateSwingMode swing_mode
The active swing mode of the climate device.
Definition climate.h:202
float target_temperature_low
The minimum target temperature of the climate device, for climate devices with split target temperatu...
Definition climate.h:189
optional< std::string > custom_preset
The active custom preset mode of the climate device.
Definition climate.h:211
float current_temperature
The current temperature of the climate device, as reported from the integration.
Definition climate.h:179
ClimateAction action
The active state of the climate device.
Definition climate.h:176
optional< ClimatePreset > preset
The active preset of the climate device.
Definition climate.h:208
float target_temperature_high
The maximum target temperature of the climate device, for climate devices with split target temperatu...
Definition climate.h:191
int8_t get_target_temperature_accuracy_decimals() const
Base class for all cover devices.
Definition cover.h:111
CoverOperation current_operation
The current operation of the cover (idle, opening, closing).
Definition cover.h:116
float tilt
The current tilt value of the cover from 0.0 to 1.0.
Definition cover.h:124
float position
The position of the cover from 0.0 (fully closed) to 1.0 (fully open).
Definition cover.h:122
bool is_fully_closed() const
Helper method to check if the cover is fully closed. Equivalent to comparing .position against 0....
Definition cover.cpp:205
virtual CoverTraits get_traits()=0
bool get_supports_position() const
std::set< std::string > get_event_types() const
Definition event.h:30
const std::string * last_event_type
Definition event.h:26
virtual FanTraits get_traits()=0
bool oscillating
The current oscillation state of the fan.
Definition fan.h:112
bool state
The current on/off state of the fan.
Definition fan.h:110
int speed
The current fan speed level.
Definition fan.h:114
bool supports_oscillation() const
Return if this fan supports oscillation.
Definition fan_traits.h:23
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:66
const std::vector< LightEffect * > & get_effects() const
Get all effects for this light state.
LightColorValues remote_values
The remote color values reported to the frontend.
Base class for all locks.
Definition lock.h:103
void add_on_log_callback(std::function< void(uint8_t, const char *, const char *, size_t)> &&callback)
Register a callback that will be called for every log message sent.
Definition logger.cpp:245
Base-class for all numbers.
Definition number.h:39
NumberTraits traits
Definition number.h:49
NumberMode get_mode() const
bool has_value() const
Definition optional.h:92
value_type const & value() const
Definition optional.h:94
Base-class for all selects.
Definition select.h:31
SelectTraits traits
Definition select.h:34
const std::vector< std::string > & get_options() const
Base-class for all sensors.
Definition sensor.h:59
int8_t get_accuracy_decimals()
Get the accuracy in decimals, using the manual override if set.
Definition sensor.cpp:25
Base class for all switches.
Definition switch.h:39
virtual bool assumed_state()
Return whether this switch uses an assumed state - i.e.
Definition switch.cpp:66
Base-class for all text inputs.
Definition text.h:24
TextTraits traits
Definition text.h:27
TextMode get_mode() const
Definition text_traits.h:31
std::string get_pattern() const
Definition text_traits.h:26
const UpdateState & state
const UpdateInfo & update_info
Base class for all valve devices.
Definition valve.h:105
bool is_fully_closed() const
Helper method to check if the valve is fully closed. Equivalent to comparing .position against 0....
Definition valve.cpp:166
float position
The position of the valve from 0.0 (fully closed) to 1.0 (fully open).
Definition valve.h:116
ValveOperation current_operation
The current operation of the valve (idle, opening, closing).
Definition valve.h:110
virtual ValveTraits get_traits()=0
bool get_supports_position() const
void try_send_nodefer(const char *message, const char *event=nullptr, uint32_t id=0, uint32_t reconnect=0)
static constexpr uint16_t MAX_CONSECUTIVE_SEND_FAILURES
Definition web_server.h:125
void deq_push_back_with_dedup_(void *source, message_generator_t *message_generator)
void deferrable_send_state(void *source, const char *event_type, message_generator_t *message_generator)
std::vector< DeferredEvent > deferred_queue_
Definition web_server.h:122
void add_new_client(WebServer *ws, AsyncWebServerRequest *request)
void deferrable_send_state(void *source, const char *event_type, message_generator_t *message_generator)
void try_send_nodefer(const char *message, const char *event=nullptr, uint32_t id=0, uint32_t reconnect=0)
void on_client_connect_(WebServer *ws, DeferredUpdateEventSource *source)
void on_client_disconnect_(DeferredUpdateEventSource *source)
This class allows users to create a web server with their ESP nodes.
Definition web_server.h:166
void setup() override
Setup the internal web server and register handlers.
void on_update(update::UpdateEntity *obj) override
static std::string text_sensor_all_json_generator(WebServer *web_server, void *source)
std::string light_json(light::LightState *obj, JsonDetail start_config)
Dump the light state as a JSON string.
std::string date_json(datetime::DateEntity *obj, JsonDetail start_config)
Dump the date state with its value as a JSON string.
std::string get_config_json()
Return the webserver configuration as JSON.
std::map< EntityBase *, SortingComponents > sorting_entitys_
Definition web_server.h:493
static std::string binary_sensor_state_json_generator(WebServer *web_server, void *source)
std::string binary_sensor_json(binary_sensor::BinarySensor *obj, bool value, JsonDetail start_config)
Dump the binary sensor state with its value as a JSON string.
static std::string button_state_json_generator(WebServer *web_server, void *source)
static std::string lock_all_json_generator(WebServer *web_server, void *source)
void on_light_update(light::LightState *obj) override
static std::string date_all_json_generator(WebServer *web_server, void *source)
std::string update_json(update::UpdateEntity *obj, JsonDetail start_config)
Dump the update state with its value as a JSON string.
void on_cover_update(cover::Cover *obj) override
static std::string text_state_json_generator(WebServer *web_server, void *source)
void handle_select_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a select request under '/select/<id>'.
std::string number_json(number::Number *obj, float value, JsonDetail start_config)
Dump the number state with its value as a JSON string.
static std::string event_state_json_generator(WebServer *web_server, void *source)
std::string cover_json(cover::Cover *obj, JsonDetail start_config)
Dump the cover state as a JSON string.
static std::string datetime_all_json_generator(WebServer *web_server, void *source)
static std::string sensor_all_json_generator(WebServer *web_server, void *source)
bool isRequestHandlerTrivial() const override
This web handle is not trivial.
WebServer(web_server_base::WebServerBase *base)
std::string text_sensor_json(text_sensor::TextSensor *obj, const std::string &value, JsonDetail start_config)
Dump the text sensor state with its value as a JSON string.
void on_number_update(number::Number *obj, float state) override
void handle_switch_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a switch request under '/switch/<id>/</turn_on/turn_off/toggle>'.
void handle_event_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a event request under '/event<id>'.
void parse_light_param_uint_(AsyncWebServerRequest *request, const char *param_name, T &call, Ret(T::*setter)(uint32_t), uint32_t scale=1)
Definition web_server.h:517
std::string button_json(button::Button *obj, JsonDetail start_config)
Dump the button details with its value as a JSON string.
std::string valve_json(valve::Valve *obj, JsonDetail start_config)
Dump the valve state as a JSON string.
DeferredUpdateEventSourceList events_
Definition web_server.h:563
void handle_button_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a button request under '/button/<id>/press'.
void on_date_update(datetime::DateEntity *obj) override
std::string text_json(text::Text *obj, const std::string &value, JsonDetail start_config)
Dump the text state with its value as a JSON string.
void add_entity_config(EntityBase *entity, float weight, uint64_t group)
std::string datetime_json(datetime::DateTimeEntity *obj, JsonDetail start_config)
Dump the datetime state with its value as a JSON string.
void handle_css_request(AsyncWebServerRequest *request)
Handle included css request under '/0.css'.
static std::string sensor_state_json_generator(WebServer *web_server, void *source)
void on_valve_update(valve::Valve *obj) override
void on_climate_update(climate::Climate *obj) override
void on_sensor_update(sensor::Sensor *obj, float state) override
static std::string switch_state_json_generator(WebServer *web_server, void *source)
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 std::string event_all_json_generator(WebServer *web_server, void *source)
static std::string climate_state_json_generator(WebServer *web_server, void *source)
void on_binary_sensor_update(binary_sensor::BinarySensor *obj) override
static std::string number_all_json_generator(WebServer *web_server, void *source)
void handle_text_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a text input request under '/text/<id>'.
void handle_cover_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a cover request under '/cover/<id>/<open/close/stop/set>'.
void on_select_update(select::Select *obj, const std::string &state, size_t index) override
static std::string date_state_json_generator(WebServer *web_server, void *source)
static std::string valve_all_json_generator(WebServer *web_server, void *source)
static std::string text_all_json_generator(WebServer *web_server, void *source)
web_server_base::WebServerBase * base_
Definition web_server.h:561
static std::string binary_sensor_all_json_generator(WebServer *web_server, void *source)
static std::string light_state_json_generator(WebServer *web_server, void *source)
void handle_lock_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a lock request under '/lock/<id>/</lock/unlock/open>'.
void on_alarm_control_panel_update(alarm_control_panel::AlarmControlPanel *obj) override
static std::string light_all_json_generator(WebServer *web_server, void *source)
std::string switch_json(switch_::Switch *obj, bool value, JsonDetail start_config)
Dump the switch state with its value as a JSON string.
void handle_text_sensor_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a text sensor request under '/text_sensor/<id>'.
std::string sensor_json(sensor::Sensor *obj, float value, JsonDetail start_config)
Dump the sensor state with its value as a JSON string.
void handle_date_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a date request under '/date/<id>'.
static std::string cover_all_json_generator(WebServer *web_server, void *source)
void handle_sensor_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a sensor request under '/sensor/<id>'.
static std::string text_sensor_state_json_generator(WebServer *web_server, void *source)
void handle_number_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a number request under '/number/<id>'.
static std::string alarm_control_panel_state_json_generator(WebServer *web_server, void *source)
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 set_js_include(const char *js_include)
Set local path to the script that's embedded in the index page.
void on_text_update(text::Text *obj, const std::string &state) override
static std::string fan_state_json_generator(WebServer *web_server, void *source)
static std::string update_state_json_generator(WebServer *web_server, void *source)
void handleRequest(AsyncWebServerRequest *request) override
Override the web handler's handleRequest method.
static std::string climate_all_json_generator(WebServer *web_server, void *source)
void on_datetime_update(datetime::DateTimeEntity *obj) override
std::string event_json(event::Event *obj, const std::string &event_type, JsonDetail start_config)
Dump the event details with its value as a JSON string.
void on_text_sensor_update(text_sensor::TextSensor *obj, const std::string &state) override
std::string time_json(datetime::TimeEntity *obj, JsonDetail start_config)
Dump the time state with its value as a JSON string.
void handle_fan_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a fan request under '/fan/<id>/</turn_on/turn_off/toggle>'.
static std::string cover_state_json_generator(WebServer *web_server, void *source)
static std::string lock_state_json_generator(WebServer *web_server, void *source)
void handle_valve_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a valve request under '/valve/<id>/<open/close/stop/set>'.
void handle_binary_sensor_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a binary sensor request under '/binary_sensor/<id>'.
static std::string alarm_control_panel_all_json_generator(WebServer *web_server, void *source)
static std::string number_state_json_generator(WebServer *web_server, void *source)
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:494
void set_css_include(const char *css_include)
Set local path to the script that's embedded in the index page.
static std::string valve_state_json_generator(WebServer *web_server, void *source)
bool canHandle(AsyncWebServerRequest *request) const override
Override the web handler's canHandle method.
std::string lock_json(lock::Lock *obj, lock::LockState value, JsonDetail start_config)
Dump the lock state with its value as a JSON string.
void handle_pna_cors_request(AsyncWebServerRequest *request)
std::string fan_json(fan::Fan *obj, JsonDetail start_config)
Dump the fan state as a JSON string.
void on_fan_update(fan::Fan *obj) override
void parse_light_param_(AsyncWebServerRequest *request, const char *param_name, T &call, Ret(T::*setter)(float), float scale=1.0f)
Definition web_server.h:505
void handle_datetime_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a datetime request under '/datetime/<id>'.
void parse_string_param_(AsyncWebServerRequest *request, const char *param_name, T &call, Ret(T::*setter)(const std::string &))
Definition web_server.h:552
void on_event(event::Event *obj, const std::string &event_type) override
void parse_float_param_(AsyncWebServerRequest *request, const char *param_name, T &call, Ret(T::*setter)(float))
Definition web_server.h:530
void handle_alarm_control_panel_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a alarm_control_panel request under '/alarm_control_panel/<id>'.
static std::string time_state_json_generator(WebServer *web_server, void *source)
void on_lock_update(lock::Lock *obj) override
static std::string button_all_json_generator(WebServer *web_server, void *source)
static std::string select_state_json_generator(WebServer *web_server, void *source)
float get_setup_priority() const override
MQTT setup priority.
void parse_int_param_(AsyncWebServerRequest *request, const char *param_name, T &call, Ret(T::*setter)(int))
Definition web_server.h:541
void on_time_update(datetime::TimeEntity *obj) override
std::string select_json(select::Select *obj, const std::string &value, JsonDetail start_config)
Dump the select state with its value as a JSON string.
static std::string update_all_json_generator(WebServer *web_server, void *source)
void on_switch_update(switch_::Switch *obj, bool state) override
void handle_update_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a update request under '/update/<id>'.
std::string climate_json(climate::Climate *obj, JsonDetail start_config)
Dump the climate details.
static std::string fan_all_json_generator(WebServer *web_server, void *source)
static std::string switch_all_json_generator(WebServer *web_server, void *source)
static std::string time_all_json_generator(WebServer *web_server, void *source)
void add_sorting_group(uint64_t group_id, const std::string &group_name, float weight)
static std::string select_all_json_generator(WebServer *web_server, void *source)
static std::string datetime_state_json_generator(WebServer *web_server, void *source)
void handle_climate_request(AsyncWebServerRequest *request, const UrlMatch &match)
Handle a climate request under '/climate/<id>'.
std::string alarm_control_panel_json(alarm_control_panel::AlarmControlPanel *obj, alarm_control_panel::AlarmControlPanelState value, JsonDetail start_config)
Dump the alarm_control_panel state with its value as a JSON string.
void add_handler(AsyncWebHandler *handler)
ClimateSwingMode swing_mode
Definition climate.h:11
uint8_t custom_preset
Definition climate.h:9
uint8_t custom_fan_mode
Definition climate.h:4
int speed
Definition fan.h:1
bool state
Definition fan.h:0
mopeka_std_values val[4]
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.
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.
const char * cover_operation_to_str(CoverOperation op)
Definition cover.cpp:21
std::string build_json(const json_build_t &f)
Build a JSON string with the provided json build function.
Definition json_util.cpp:33
LockState
Enum for all states a lock can be in.
Definition lock.h:26
const char * lock_state_to_string(LockState state)
Definition lock.cpp:9
Logger * global_logger
Definition logger.cpp:283
std::string get_use_address()
Get the active network hostname.
Definition util.cpp:88
const char *const TAG
Definition spi.cpp:8
const char * valve_operation_to_str(ValveOperation op)
Definition valve.cpp:21
std::string(WebServer *, void *) message_generator_t
Definition web_server.h:85
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
std::string value_accuracy_to_string(float value, int8_t accuracy_decimals)
Create a string from a value and an accuracy in decimals.
Definition helpers.cpp:339
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:324
std::string get_mac_address_pretty()
Get the device MAC address as a string, in colon-separated uppercase hex notation.
Definition helpers.cpp:584
int8_t step_to_accuracy_decimals(float step)
Derive accuracy in decimals from an increment step.
Definition helpers.cpp:350
std::string str_sprintf(const char *fmt,...)
Definition helpers.cpp:208
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:28
Application App
Global storage of Application pointer - only one Application can exist.
T id(T value)
Helper function to make id(var) known from lambdas work in custom components.
Definition helpers.h:933
@ PARSE_ON
Definition helpers.h:553
@ PARSE_TOGGLE
Definition helpers.h:555
@ PARSE_OFF
Definition helpers.h:554
@ PARSE_NONE
Definition helpers.h:552
Internal helper struct that is used to parse incoming URLs.
Definition web_server.h:37
const char * domain
Pointer to domain within URL, for example "sensor".
Definition web_server.h:38
bool valid
Whether this match is valid.
Definition web_server.h:44
bool domain_equals(const char *str) const
Definition web_server.h:47
bool method_equals(const char *str) const
Definition web_server.h:55
bool id_equals(const std::string &str) const
Definition web_server.h:51
uint8_t end[39]
Definition sun_gtil2.cpp:17
friend class DeferredUpdateEventSource
Definition web_server.h:0
const size_t ESPHOME_WEBSERVER_INDEX_HTML_SIZE
const size_t ESPHOME_WEBSERVER_CSS_INCLUDE_SIZE
const size_t ESPHOME_WEBSERVER_JS_INCLUDE_SIZE