ESPHome 2025.12.0-dev
Loading...
Searching...
No Matches
mdns_esp32.cpp
Go to the documentation of this file.
2#if defined(USE_ESP32) && defined(USE_MDNS)
3
4#include <mdns.h>
6#include "esphome/core/hal.h"
7#include "esphome/core/log.h"
8#include "mdns_component.h"
9
10namespace esphome {
11namespace mdns {
12
13static const char *const TAG = "mdns";
14
16#ifdef USE_MDNS_STORE_SERVICES
17 this->compile_records_(this->services_);
18 const auto &services = this->services_;
19#else
21 this->compile_records_(services);
22#endif
23
24 esp_err_t err = mdns_init();
25 if (err != ESP_OK) {
26 ESP_LOGW(TAG, "Init failed: %s", esp_err_to_name(err));
27 this->mark_failed();
28 return;
29 }
30
31 const char *hostname = App.get_name().c_str();
32 mdns_hostname_set(hostname);
33 mdns_instance_name_set(hostname);
34
35 for (const auto &service : services) {
36 auto txt_records = std::make_unique<mdns_txt_item_t[]>(service.txt_records.size());
37 for (size_t i = 0; i < service.txt_records.size(); i++) {
38 const auto &record = service.txt_records[i];
39 // key and value are either compile-time string literals in flash or pointers to dynamic_txt_values_
40 // Both remain valid for the lifetime of this function, and ESP-IDF makes internal copies
41 txt_records[i].key = MDNS_STR_ARG(record.key);
42 txt_records[i].value = MDNS_STR_ARG(record.value);
43 }
44 uint16_t port = const_cast<TemplatableValue<uint16_t> &>(service.port).value();
45 err = mdns_service_add(nullptr, MDNS_STR_ARG(service.service_type), MDNS_STR_ARG(service.proto), port,
46 txt_records.get(), service.txt_records.size());
47
48 if (err != ESP_OK) {
49 ESP_LOGW(TAG, "Failed to register service %s: %s", MDNS_STR_ARG(service.service_type), esp_err_to_name(err));
50 }
51 }
52}
53
55 mdns_free();
56 delay(40); // Allow the mdns packets announcing service removal to be sent
57}
58
59} // namespace mdns
60} // namespace esphome
61
62#endif // USE_ESP32
const std::string & get_name() const
Get the name of this Application set by pre_setup().
virtual void mark_failed()
Mark this component as failed.
Minimal static vector - saves memory by avoiding std::vector overhead.
Definition helpers.h:132
void compile_records_(StaticVector< MDNSService, MDNS_SERVICE_COUNT > &services)
StaticVector< MDNSService, MDNS_SERVICE_COUNT > services_
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:31
Application App
Global storage of Application pointer - only one Application can exist.