ESPHome 2026.10.2
Loading...
Searching...
No Matches
mdns_component.h
Go to the documentation of this file.
1#pragma once
3#ifdef USE_MDNS
4#include <string>
9// On ESP8266 and RP2040 the scheduler-backed MDNS.update() polling window is armed by
10// IP state listener events on whichever network interface is configured.
11#if (defined(USE_ESP8266) || defined(USE_RP2)) && \
12 ((defined(USE_WIFI) && defined(USE_WIFI_IP_STATE_LISTENERS)) || \
13 (defined(USE_ETHERNET) && defined(USE_ETHERNET_IP_STATE_LISTENERS)))
15#define USE_MDNS_EVENT_DRIVEN_POLLING
16#if defined(USE_WIFI) && defined(USE_WIFI_IP_STATE_LISTENERS)
18#define USE_MDNS_WIFI_LISTENER
19#endif
20#if defined(USE_ETHERNET) && defined(USE_ETHERNET_IP_STATE_LISTENERS)
22#define USE_MDNS_ETHERNET_LISTENER
23#endif
24#endif
25
26// Device info TXT records (version, mac, config_hash) are published on the _esphomelib service
27// when the native API is enabled, otherwise on the _http service (web_server's or the fallback one).
28// When neither applies (only prometheus, sendspin or user-defined services are configured), no
29// device info records are published and the buffers below are not needed.
30#if defined(USE_API) || defined(USE_WEBSERVER) || \
31 (!defined(USE_PROMETHEUS) && !defined(USE_SENDSPIN) && !defined(USE_MDNS_EXTRA_SERVICES))
32#define USE_MDNS_DEVICE_INFO_TXT
33#endif
34
35// With both wifi and ethernet, the _esphomelib "network" TXT value follows the connected interface.
36// OpenThread hands its services to the SRP client once, so it keeps the fixed value.
37#if defined(USE_API) && defined(USE_WIFI) && defined(USE_ETHERNET) && !defined(USE_OPENTHREAD)
38#define USE_MDNS_DYNAMIC_NETWORK_TXT
39#endif
40
41namespace esphome::mdns {
42
43// Helper struct that identifies strings that may be stored in flash storage (similar to LogString)
44struct MDNSString;
45
46// Macro to cast string literals to MDNSString* (works on all platforms)
47#define MDNS_STR(name) (reinterpret_cast<const esphome::mdns::MDNSString *>(name))
48
49#define MDNS_STR_ARG(s) (reinterpret_cast<ESPHOME_PGM_P>(s))
50
51// Service count is calculated at compile time by Python codegen
52// MDNS_SERVICE_COUNT will always be defined
53
55 const MDNSString *key;
56 const MDNSString *value;
57};
58
60 // service name _including_ underscore character prefix
61 // as defined in RFC6763 Section 7
62 const MDNSString *service_type;
63 // second label indicating protocol _including_ underscore character prefix
64 // as defined in RFC6763 Section 7, like "_tcp" or "_udp"
65 const MDNSString *proto;
68#ifdef USE_MDNS_SUPPORTS_ENABLE_DISABLE
69 bool enabled{true};
70#endif
71};
72
73class MDNSComponent final : public Component
74#ifdef USE_MDNS_WIFI_LISTENER
75 ,
77#endif
78#ifdef USE_MDNS_ETHERNET_LISTENER
79 ,
81#endif
82{
83 public:
84 void setup() override;
85 void dump_config() override;
86
88 static constexpr size_t CONFIG_HASH_STR_SIZE = format_hex_size(sizeof(uint32_t));
89
90#ifdef USE_MDNS_EVENT_DRIVEN_POLLING
91 // LEAmDNS has meaningful work only during the probe+announce phase (3×250ms probes +
92 // 8×1000ms announces, ~9s). Afterwards every internal timer is resetToNeverExpires()
93 // and update() becomes pure overhead. We arm a bounded polling window from IP state
94 // listener events so update() runs only during that phase.
95 static constexpr uint32_t MDNS_UPDATE_INTERVAL_MS = 50;
96 // Must exceed LEAmDNS's longest restart-to-announce-complete path:
97 // MDNS_PROBE_DELAY (250ms) × MDNS_PROBE_COUNT (3) = 750ms probing
98 // + MDNS_ANNOUNCE_DELAY (1000ms) × MDNS_ANNOUNCE_COUNT (8) = 8000ms announcing
99 // + rand() % MDNS_PROBE_DELAY jitter on first probe (0–250ms)
100 // + debounced schedule_function() hop when statusChangeCB fires on ESP8266
101 // ≈ 9s nominal. 15s gives ~6s margin to absorb main-loop blocking (long
102 // component setup, WiFi scan, flash writes) that could stretch the deadlines
103 // between our polls. If LEAmDNS ever extends its phase (upstream library
104 // update) this constant needs to grow. Constants defined in LEAmDNS_Priv.h
105 // (ESP8266 core 3.1.2 / arduino-pico 5.5.1).
106 static constexpr uint32_t MDNS_POLL_WINDOW_MS = 15000;
107 static constexpr uint32_t MDNS_POLL_ID = 0;
108 static constexpr uint32_t MDNS_POLL_STOP_ID = 1;
109#endif
110 float get_setup_priority() const override { return setup_priority::AFTER_CONNECTION; }
111
112#ifdef USE_MDNS_EXTRA_SERVICES
113 void add_extra_service(MDNSService service) { this->services_.emplace_next() = std::move(service); }
114#endif
115
116#ifdef USE_MDNS_STORE_SERVICES
118#endif
119
120#ifdef USE_MDNS_SUPPORTS_ENABLE_DISABLE
121#ifndef USE_MDNS_STORE_SERVICES
122#error "USE_MDNS_SUPPORTS_ENABLE_DISABLE requires USE_MDNS_STORE_SERVICES"
123#endif
124#ifdef USE_OPENTHREAD
125#error "USE_MDNS_SUPPORTS_ENABLE_DISABLE is not supported with OpenThread"
126#endif
130 bool set_service_enabled(const char *service_type, const char *proto, bool enabled);
131#endif
132
133 void on_shutdown() override;
134
135#ifdef USE_MDNS_DYNAMIC_TXT
137 const char *add_dynamic_txt_value(const std::string &value) {
138 this->dynamic_txt_values_.push_back(value);
139 return this->dynamic_txt_values_[this->dynamic_txt_values_.size() - 1].c_str();
140 }
141#endif
142
143#ifdef USE_MDNS_EVENT_DRIVEN_POLLING
144 void on_ip_state(const network::IPAddresses &ips, const network::IPAddress &dns1,
145 const network::IPAddress &dns2) override;
146#endif
147
148 protected:
149#ifdef USE_MDNS_EVENT_DRIVEN_POLLING
153#endif
156
157 void setup_buffers_and_register_(PlatformRegisterFn platform_register);
158
159#ifdef USE_MDNS_DYNAMIC_NETWORK_TXT
162 const char *connected_network_() const;
164 void update_network_txt_();
166 bool publish_network_txt_(const char *network);
168 const char *network_txt_{nullptr};
169#ifdef USE_MDNS_STORE_SERVICES
172#endif
173#endif
174
175#ifdef USE_MDNS_DYNAMIC_TXT
180#endif
181
182#if defined(USE_MDNS_DEVICE_INFO_TXT) && defined(USE_MDNS_STORE_SERVICES)
184 char mac_address_[MAC_ADDRESS_BUFFER_SIZE];
187#endif
188#ifdef USE_MDNS_STORE_SERVICES
190#endif
191#if defined(USE_RP2) && defined(USE_MDNS_EVENT_DRIVEN_POLLING)
192 // RP2040 defers MDNS.begin() until the first IP-up event; this tracks that.
193 bool initialized_{false};
194#endif
195 void compile_records_(StaticVector<MDNSService, MDNS_SERVICE_COUNT> &services, const char *mac_address_buf,
196 const char *config_hash_buf);
197};
198
199} // namespace esphome::mdns
200#endif
Fixed-capacity vector - sized once through init() or try_init(); push_back never reallocates This avo...
Definition helpers.h:621
Minimal static vector - saves memory by avoiding std::vector overhead.
Definition helpers.h:291
size_t size() const
Definition helpers.h:360
void push_back(const T &value)
Definition helpers.h:330
Function-pointer-only templatable storage (4 bytes on 32-bit).
Definition automation.h:20
Listener interface for Ethernet IP state changes.
const char * connected_network_() const
The first connected interface in network: priority order ("ethernet" or "wifi"), else nullptr.
const char * network_txt_
Advertised value; nullptr until the _esphomelib service is registered, and after a failed publish.
void update_network_txt_()
Check the connected interface and publish a changed "network" TXT value.
StaticVector< std::string, MDNS_DYNAMIC_TXT_COUNT > dynamic_txt_values_
Storage for runtime-generated TXT values from user lambdas Pre-sized at compile time via MDNS_DYNAMIC...
static constexpr uint32_t MDNS_POLL_STOP_ID
void start_polling_window_()
Arm a fresh MDNS_POLL_WINDOW_MS polling window.
float get_setup_priority() const override
void on_ip_state(const network::IPAddresses &ips, const network::IPAddress &dns1, const network::IPAddress &dns2) override
const char * add_dynamic_txt_value(const std::string &value)
Add a dynamic TXT value and return pointer to it for use in MDNSTXTRecord.
char config_hash_str_[CONFIG_HASH_STR_SIZE]
Fixed buffer for config hash hex string (only needed when services are stored)
static constexpr size_t CONFIG_HASH_STR_SIZE
Size of buffer required for config hash hex string (8 hex chars + null terminator)
bool set_service_enabled(const char *service_type, const char *proto, bool enabled)
Enable or disable a compiled-in service, matched by type and proto (e.g.
void compile_records_(StaticVector< MDNSService, MDNS_SERVICE_COUNT > &services, const char *mac_address_buf, const char *config_hash_buf)
static constexpr uint32_t MDNS_POLL_WINDOW_MS
void setup_buffers_and_register_(PlatformRegisterFn platform_register)
char mac_address_[MAC_ADDRESS_BUFFER_SIZE]
Fixed buffer for MAC address (only needed when services are stored)
void(*)(MDNSComponent *, StaticVector< MDNSService, MDNS_SERVICE_COUNT > &) PlatformRegisterFn
Helper to set up services and MAC buffers, then call platform-specific registration.
void add_extra_service(MDNSService service)
static constexpr uint32_t MDNS_POLL_ID
MDNSTXTRecord * network_record_
The "network" record in services_, kept in step with network_txt_.
static constexpr uint32_t MDNS_UPDATE_INTERVAL_MS
static constexpr uint32_t NETWORK_TXT_CHECK_INTERVAL_MS
const StaticVector< MDNSService, MDNS_SERVICE_COUNT > & get_services() const
bool publish_network_txt_(const char *network)
Platform-specific: replace the "network" TXT value of the registered _esphomelib service.
StaticVector< MDNSService, MDNS_SERVICE_COUNT > services_
Listener interface for WiFi IP state changes.
std::array< IPAddress, 5 > IPAddresses
Definition ip_address.h:292
constexpr float AFTER_CONNECTION
For components that should be initialized after a data connection (API/MQTT) is connected.
Definition component.h:57
constexpr size_t format_hex_size(size_t byte_count)
Calculate buffer size needed for format_hex_to: "XXXXXXXX...\0" = bytes * 2 + 1.
Definition helpers.h:1506
static void uint32_t
FixedVector< MDNSTXTRecord > txt_records
const MDNSString * proto
TemplatableFn< uint16_t > port
const MDNSString * service_type