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