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