ESPHome  2024.4.1
mdns_esp32.cpp
Go to the documentation of this file.
1 #ifdef USE_ESP32
2 
3 #include <mdns.h>
4 #include <cstring>
5 #include "esphome/core/hal.h"
6 #include "esphome/core/log.h"
7 #include "mdns_component.h"
8 
9 namespace esphome {
10 namespace mdns {
11 
12 static const char *const TAG = "mdns";
13 
15  this->compile_records_();
16 
17  esp_err_t err = mdns_init();
18  if (err != ESP_OK) {
19  ESP_LOGW(TAG, "mDNS init failed: %s", esp_err_to_name(err));
20  this->mark_failed();
21  return;
22  }
23 
24  mdns_hostname_set(this->hostname_.c_str());
25  mdns_instance_name_set(this->hostname_.c_str());
26 
27  for (const auto &service : this->services_) {
28  std::vector<mdns_txt_item_t> txt_records;
29  for (const auto &record : service.txt_records) {
30  mdns_txt_item_t it{};
31  // dup strings to ensure the pointer is valid even after the record loop
32  it.key = strdup(record.key.c_str());
33  it.value = strdup(record.value.c_str());
34  txt_records.push_back(it);
35  }
36  err = mdns_service_add(nullptr, service.service_type.c_str(), service.proto.c_str(), service.port,
37  txt_records.data(), txt_records.size());
38 
39  // free records
40  for (const auto &it : txt_records) {
41  delete it.key; // NOLINT(cppcoreguidelines-owning-memory)
42  delete it.value; // NOLINT(cppcoreguidelines-owning-memory)
43  }
44 
45  if (err != ESP_OK) {
46  ESP_LOGW(TAG, "Failed to register mDNS service %s: %s", service.service_type.c_str(), esp_err_to_name(err));
47  }
48  }
49 }
50 
52  mdns_free();
53  delay(40); // Allow the mdns packets announcing service removal to be sent
54 }
55 
56 } // namespace mdns
57 } // namespace esphome
58 
59 #endif // USE_ESP32
std::vector< MDNSService > services_
void on_shutdown() override
Definition: mdns_esp32.cpp:51
virtual void mark_failed()
Mark this component as failed.
Definition: component.cpp:118
This is a workaround until we can figure out a way to get the tflite-micro idf component code availab...
Definition: a01nyub.cpp:7
void IRAM_ATTR HOT delay(uint32_t ms)
Definition: core.cpp:26