ESPHome  2022.12.8
mdns_esp_idf.cpp
Go to the documentation of this file.
1 #ifdef USE_ESP_IDF
2 
3 #include "mdns_component.h"
4 #include "esphome/core/log.h"
5 #include <mdns.h>
6 #include <cstring>
7 
8 namespace esphome {
9 namespace mdns {
10 
11 static const char *const TAG = "mdns";
12 
13 void MDNSComponent::setup() {
14  this->compile_records_();
15 
16  esp_err_t err = mdns_init();
17  if (err != ESP_OK) {
18  ESP_LOGW(TAG, "mDNS init failed: %s", esp_err_to_name(err));
19  this->mark_failed();
20  return;
21  }
22 
23  mdns_hostname_set(this->hostname_.c_str());
24  mdns_instance_name_set(this->hostname_.c_str());
25 
26  for (const auto &service : this->services_) {
27  std::vector<mdns_txt_item_t> txt_records;
28  for (const auto &record : service.txt_records) {
29  mdns_txt_item_t it{};
30  // dup strings to ensure the pointer is valid even after the record loop
31  it.key = strdup(record.key.c_str());
32  it.value = strdup(record.value.c_str());
33  txt_records.push_back(it);
34  }
35  err = mdns_service_add(nullptr, service.service_type.c_str(), service.proto.c_str(), service.port,
36  txt_records.data(), txt_records.size());
37 
38  // free records
39  for (const auto &it : txt_records) {
40  delete it.key; // NOLINT(cppcoreguidelines-owning-memory)
41  delete it.value; // NOLINT(cppcoreguidelines-owning-memory)
42  }
43 
44  if (err != ESP_OK) {
45  ESP_LOGW(TAG, "Failed to register mDNS service %s: %s", service.service_type.c_str(), esp_err_to_name(err));
46  }
47  }
48 }
49 
50 } // namespace mdns
51 } // namespace esphome
52 
53 #endif
std::vector< MDNSService > services_
virtual void mark_failed()
Mark this component as failed.
Definition: component.cpp:112
Definition: a4988.cpp:4