ESPHome 2026.6.2
Loading...
Searching...
No Matches
ethernet_component_esp32.cpp
Go to the documentation of this file.
2
3#if defined(USE_ETHERNET) && defined(USE_ESP32)
4
7#include "esphome/core/log.h"
8#include "w5500_custom_spi.h"
9
10#include <lwip/dns.h>
11#include <cinttypes>
12#include "esp_event.h"
13
14// IDF 6.0 moved per-chip PHY/MAC drivers to the Espressif Component Registry;
15// they are no longer included via esp_eth.h and need explicit includes.
16// On IDF 5.x these headers don't exist as standalone files.
17#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
18#ifdef USE_ETHERNET_LAN8720
19#include "esp_eth_phy_lan87xx.h"
20#endif
21#ifdef USE_ETHERNET_RTL8201
22#include "esp_eth_phy_rtl8201.h"
23#endif
24#ifdef USE_ETHERNET_DP83848
25#include "esp_eth_phy_dp83848.h"
26#endif
27#ifdef USE_ETHERNET_IP101
28#include "esp_eth_phy_ip101.h"
29#endif
30#ifdef USE_ETHERNET_KSZ8081
31#include "esp_eth_phy_ksz80xx.h"
32#endif
33#ifdef USE_ETHERNET_W5500
34#include "esp_eth_mac_w5500.h"
35#include "esp_eth_phy_w5500.h"
36#endif
37#ifdef USE_ETHERNET_DM9051
38#include "esp_eth_mac_dm9051.h"
39#include "esp_eth_phy_dm9051.h"
40#endif
41#endif // ESP_IDF_VERSION >= 6.0.0
42
43// LAN867x header exists on all IDF versions (external component since IDF 5.3)
44#ifdef USE_ETHERNET_LAN8670
45#include "esp_eth_phy_lan867x.h"
46#endif
47
48// ENC28J60 header exists on all IDF versions (always an external component)
49#ifdef USE_ETHERNET_ENC28J60
50#include "esp_eth_enc28j60.h"
51#endif
52
53#ifdef USE_ETHERNET_SPI
54#include <driver/gpio.h>
55#include <driver/spi_master.h>
56#endif
57
58namespace esphome::ethernet {
59
60static const char *const TAG = "ethernet";
61
62// PHY register size for hex logging
63static constexpr size_t PHY_REG_SIZE = 2;
64
66 ESP_LOGE(TAG, "%s: (%d) %s", message, err, esp_err_to_name(err));
67 this->mark_failed();
68}
69
70#define ESPHL_ERROR_CHECK(err, message) \
71 if ((err) != ESP_OK) { \
72 this->log_error_and_mark_failed_(err, message); \
73 return; \
74 }
75
76#define ESPHL_ERROR_CHECK_RET(err, message, ret) \
77 if ((err) != ESP_OK) { \
78 this->log_error_and_mark_failed_(err, message); \
79 return ret; \
80 }
81
84
85 switch (this->state_) {
87 if (this->started_) {
88 ESP_LOGI(TAG, "Starting connection");
90 this->start_connect_();
91 }
92 break;
94 if (!this->started_) {
95 ESP_LOGI(TAG, "Stopped connection");
97 } else if (this->connected_) {
98 // connection established
99 ESP_LOGI(TAG, "Connected");
101
102 this->dump_connect_params_();
103 this->status_clear_warning();
104#ifdef USE_ETHERNET_CONNECT_TRIGGER
106#endif
107 } else if (now - this->connect_begin_ > 15000) {
108 ESP_LOGW(TAG, "Connecting failed; reconnecting");
109 this->start_connect_();
110 }
111 break;
113 if (!this->started_) {
114 ESP_LOGI(TAG, "Stopped connection");
116#ifdef USE_ETHERNET_DISCONNECT_TRIGGER
118#endif
119 } else if (!this->connected_) {
120 ESP_LOGW(TAG, "Connection lost; reconnecting");
122 this->start_connect_();
123#ifdef USE_ETHERNET_DISCONNECT_TRIGGER
125#endif
126 } else {
127 this->finish_connect_();
128 // When connected and stable, disable the loop to save CPU cycles
129 this->disable_loop();
130 }
131 break;
132 }
133}
134
136 if (esp_reset_reason() != ESP_RST_DEEPSLEEP) {
137 // Delay here to allow power to stabilise before Ethernet is initialized.
138 delay(300); // NOLINT
139 }
140
141 if (this->enable_on_boot_) {
142 this->ethernet_lazy_init_();
143 if (!this->ethernet_initialized_) {
144 // lazy_init bailed early via ESPHL_ERROR_CHECK or mark_failed; nothing more to do.
145 return;
146 }
147 esp_err_t err = esp_eth_start(this->eth_handle_);
148 ESPHL_ERROR_CHECK(err, "ETH start error");
149 } else {
150 ESP_LOGCONFIG(TAG, "Skipping init (enable_on_boot: false)");
151 this->disabled_ = true;
152 }
153}
154
156 if (this->ethernet_initialized_)
157 return;
158
159 esp_err_t err;
160
161#ifdef USE_ETHERNET_SPI
162 // Install GPIO ISR handler to be able to service SPI Eth modules interrupts
163 gpio_install_isr_service(0);
164
165 spi_bus_config_t buscfg = {
166 .mosi_io_num = this->mosi_pin_,
167 .miso_io_num = this->miso_pin_,
168 .sclk_io_num = this->clk_pin_,
169 .quadwp_io_num = -1,
170 .quadhd_io_num = -1,
171 .data4_io_num = -1,
172 .data5_io_num = -1,
173 .data6_io_num = -1,
174 .data7_io_num = -1,
175 .max_transfer_sz = 0,
176 .flags = 0,
177 .intr_flags = 0,
178 };
179
180 auto host = this->interface_;
181
182 err = spi_bus_initialize(host, &buscfg, SPI_DMA_CH_AUTO);
183 ESPHL_ERROR_CHECK(err, "SPI bus initialize error");
184#endif
185 // Network interface setup handled by network component
186
187 esp_netif_config_t cfg = ESP_NETIF_DEFAULT_ETH();
188 this->eth_netif_ = esp_netif_new(&cfg);
189
190 // Init MAC and PHY configs to default
191 eth_phy_config_t phy_config = ETH_PHY_DEFAULT_CONFIG();
192 eth_mac_config_t mac_config = ETH_MAC_DEFAULT_CONFIG();
193
194#ifdef USE_ETHERNET_SPI // Configure SPI interface and Ethernet driver for specific SPI module
195 spi_device_interface_config_t devcfg = {
196 .command_bits = 0,
197 .address_bits = 0,
198 .dummy_bits = 0,
199 .mode = 0,
200 .duty_cycle_pos = 0,
201 .cs_ena_pretrans = 0,
202 .cs_ena_posttrans = 0,
203 .clock_speed_hz = this->clock_speed_,
204 .input_delay_ns = 0,
205 .spics_io_num = this->cs_pin_,
206 .flags = 0,
207 .queue_size = 20,
208 .pre_cb = nullptr,
209 .post_cb = nullptr,
210 };
211
212#if defined(USE_ETHERNET_W5500)
213 eth_w5500_config_t w5500_config = ETH_W5500_DEFAULT_CONFIG(host, &devcfg);
214#elif defined(USE_ETHERNET_DM9051)
215 eth_dm9051_config_t dm9051_config = ETH_DM9051_DEFAULT_CONFIG(host, &devcfg);
216#elif defined(USE_ETHERNET_ENC28J60)
217 eth_enc28j60_config_t enc28j60_config = ETH_ENC28J60_DEFAULT_CONFIG(host, &devcfg);
218#endif
219
220#if defined(USE_ETHERNET_W5500)
221 w5500_config.int_gpio_num = this->interrupt_pin_;
222#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
223 w5500_config.poll_period_ms = this->polling_interval_;
224#endif
225 // Install the custom SPI driver that offloads the bulk RX/TX frame transfers off the busy-wait
226 // path. w5500_config (and the devcfg it references) outlives esp_eth_mac_new_w5500() below, which
227 // runs the driver's init().
228 install_w5500_async_spi(w5500_config);
229#elif defined(USE_ETHERNET_DM9051)
230 dm9051_config.int_gpio_num = this->interrupt_pin_;
231#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
232 dm9051_config.poll_period_ms = this->polling_interval_;
233#endif
234#elif defined(USE_ETHERNET_ENC28J60)
235 enc28j60_config.int_gpio_num = this->interrupt_pin_;
236 // ENC28J60 does not support poll_period_ms
237#endif
238
239 phy_config.phy_addr = this->phy_addr_spi_;
240 phy_config.reset_gpio_num = this->reset_pin_;
241
242 esp_eth_mac_t *mac = nullptr;
243#elif defined(USE_ETHERNET_OPENETH)
244 esp_eth_mac_t *mac = esp_eth_mac_new_openeth(&mac_config);
245#else
246 phy_config.phy_addr = this->phy_addr_;
247 phy_config.reset_gpio_num = this->power_pin_;
248
249 eth_esp32_emac_config_t esp32_emac_config = eth_esp32_emac_default_config();
250#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 0)
251 esp32_emac_config.smi_gpio.mdc_num = this->mdc_pin_;
252 esp32_emac_config.smi_gpio.mdio_num = this->mdio_pin_;
253#else
254 esp32_emac_config.smi_mdc_gpio_num = this->mdc_pin_;
255 esp32_emac_config.smi_mdio_gpio_num = this->mdio_pin_;
256#endif
257 esp32_emac_config.clock_config.rmii.clock_mode = this->clk_mode_;
258 esp32_emac_config.clock_config.rmii.clock_gpio =
259 static_cast<decltype(esp32_emac_config.clock_config.rmii.clock_gpio)>(this->clk_pin_);
260
261 esp_eth_mac_t *mac = esp_eth_mac_new_esp32(&esp32_emac_config, &mac_config);
262#endif
263
264 switch (this->type_) {
265#ifdef USE_ETHERNET_OPENETH
267 phy_config.autonego_timeout_ms = 1000;
268#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
269 this->phy_ = esp_eth_phy_new_generic(&phy_config);
270#else
271 this->phy_ = esp_eth_phy_new_dp83848(&phy_config);
272#endif
273 break;
274 }
275#endif
276#if CONFIG_ETH_USE_ESP32_EMAC
277#ifdef USE_ETHERNET_LAN8720
279 this->phy_ = esp_eth_phy_new_lan87xx(&phy_config);
280 break;
281 }
282#endif
283#ifdef USE_ETHERNET_RTL8201
285 this->phy_ = esp_eth_phy_new_rtl8201(&phy_config);
286 break;
287 }
288#endif
289#ifdef USE_ETHERNET_DP83848
291 this->phy_ = esp_eth_phy_new_dp83848(&phy_config);
292 break;
293 }
294#endif
295#ifdef USE_ETHERNET_IP101
296 case ETHERNET_TYPE_IP101: {
297 this->phy_ = esp_eth_phy_new_ip101(&phy_config);
298 break;
299 }
300#endif
301#ifdef USE_ETHERNET_JL1101
303 // PlatformIO (pioarduino): builtin esp_eth_phy_new_jl1101() on all IDF versions
304 // Non-PlatformIO: custom ESPHome driver (esp_eth_phy_jl1101.c)
305 this->phy_ = esp_eth_phy_new_jl1101(&phy_config);
306 break;
307 }
308#endif
309#ifdef USE_ETHERNET_KSZ8081
312 this->phy_ = esp_eth_phy_new_ksz80xx(&phy_config);
313 break;
314 }
315#endif
316#ifdef USE_ETHERNET_LAN8670
318 this->phy_ = esp_eth_phy_new_lan867x(&phy_config);
319 break;
320 }
321#endif
322#endif
323#ifdef USE_ETHERNET_SPI
324#if defined(USE_ETHERNET_W5500)
325 case ETHERNET_TYPE_W5500: {
326 mac = esp_eth_mac_new_w5500(&w5500_config, &mac_config);
327 this->phy_ = esp_eth_phy_new_w5500(&phy_config);
328 break;
329 }
330#elif defined(USE_ETHERNET_DM9051)
332 mac = esp_eth_mac_new_dm9051(&dm9051_config, &mac_config);
333 this->phy_ = esp_eth_phy_new_dm9051(&phy_config);
334 break;
335 }
336#elif defined(USE_ETHERNET_ENC28J60)
338 mac = esp_eth_mac_new_enc28j60(&enc28j60_config, &mac_config);
339 this->phy_ = esp_eth_phy_new_enc28j60(&phy_config);
340 break;
341 }
342#endif
343#endif
344 default: {
345 this->mark_failed();
346 return;
347 }
348 }
349
350 esp_eth_config_t eth_config = ETH_DEFAULT_CONFIG(mac, this->phy_);
351 this->eth_handle_ = nullptr;
352 err = esp_eth_driver_install(&eth_config, &this->eth_handle_);
353 ESPHL_ERROR_CHECK(err, "ETH driver install error");
354
355#ifndef USE_ETHERNET_SPI
356#ifdef USE_ETHERNET_KSZ8081
357 if (this->type_ == ETHERNET_TYPE_KSZ8081RNA && this->clk_mode_ == EMAC_CLK_OUT) {
358 // KSZ8081RNA default is incorrect. It expects a 25MHz clock instead of the 50MHz we provide.
360 }
361#endif // USE_ETHERNET_KSZ8081
362
363 for (const auto &phy_register : this->phy_registers_) {
364 this->write_phy_register_(mac, phy_register);
365 }
366#endif
367
368 // use ESP internal eth mac
369 uint8_t mac_addr[6];
370 if (this->fixed_mac_.has_value()) {
371 memcpy(mac_addr, this->fixed_mac_->data(), 6);
372 } else {
373 esp_read_mac(mac_addr, ESP_MAC_ETH);
374 }
375 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_S_MAC_ADDR, mac_addr);
376 ESPHL_ERROR_CHECK(err, "set mac address error");
377
378 /* attach Ethernet driver to TCP/IP stack */
379 err = esp_netif_attach(this->eth_netif_, esp_eth_new_netif_glue(this->eth_handle_));
380 ESPHL_ERROR_CHECK(err, "ETH netif attach error");
381
382 // Register user defined event handers
383 err = esp_event_handler_register(ETH_EVENT, ESP_EVENT_ANY_ID, &EthernetComponent::eth_event_handler, nullptr);
384 ESPHL_ERROR_CHECK(err, "ETH event handler register error");
385 err = esp_event_handler_register(IP_EVENT, IP_EVENT_ETH_GOT_IP, &EthernetComponent::got_ip_event_handler, nullptr);
386 ESPHL_ERROR_CHECK(err, "GOT IP event handler register error");
387#if USE_NETWORK_IPV6
388 err = esp_event_handler_register(IP_EVENT, IP_EVENT_GOT_IP6, &EthernetComponent::got_ip6_event_handler, nullptr);
389 ESPHL_ERROR_CHECK(err, "GOT IPv6 event handler register error");
390#endif /* USE_NETWORK_IPV6 */
391
392 this->ethernet_initialized_ = true;
393}
394
396 if (!this->disabled_)
397 return;
398
399 ESP_LOGD(TAG, "Enabling");
400 this->ethernet_lazy_init_();
401 if (!this->ethernet_initialized_) {
402 ESP_LOGE(TAG, "Cannot enable - init failed");
403 return;
404 }
405 esp_err_t err = esp_eth_start(this->eth_handle_);
406 if (err != ESP_OK) {
407 ESP_LOGE(TAG, "esp_eth_start failed: %s", esp_err_to_name(err));
408 return;
409 }
410 this->disabled_ = false;
411 // The ETH_EVENT_START handler will set started_=true; the loop state machine
412 // will then drive the STOPPED -> CONNECTING -> CONNECTED transitions.
413 this->enable_loop();
414}
415
417 if (this->disabled_)
418 return;
419
420 ESP_LOGD(TAG, "Disabling");
421 esp_err_t err = esp_eth_stop(this->eth_handle_);
422 if (err != ESP_OK) {
423 ESP_LOGW(TAG, "esp_eth_stop failed: %s — disabling anyway", esp_err_to_name(err));
424 }
425 this->disabled_ = true;
426 // ETH_EVENT_STOP will clear started_; loop() will transition to STOPPED.
427}
428
430 const char *eth_type;
431 switch (this->type_) {
432#ifdef USE_ETHERNET_LAN8720
434 eth_type = "LAN8720";
435 break;
436#endif
437#ifdef USE_ETHERNET_RTL8201
439 eth_type = "RTL8201";
440 break;
441#endif
442#ifdef USE_ETHERNET_DP83848
444 eth_type = "DP83848";
445 break;
446#endif
447#ifdef USE_ETHERNET_IP101
449 eth_type = "IP101";
450 break;
451#endif
452#ifdef USE_ETHERNET_JL1101
454 eth_type = "JL1101";
455 break;
456#endif
457#ifdef USE_ETHERNET_KSZ8081
459 eth_type = "KSZ8081";
460 break;
461
463 eth_type = "KSZ8081RNA";
464 break;
465#endif
466#if defined(USE_ETHERNET_W5500)
468 eth_type = "W5500";
469 break;
470#elif defined(USE_ETHERNET_DM9051)
472 eth_type = "DM9051";
473 break;
474#elif defined(USE_ETHERNET_ENC28J60)
476 eth_type = "ENC28J60";
477 break;
478#endif
479#ifdef USE_ETHERNET_OPENETH
481 eth_type = "OPENETH";
482 break;
483#endif
484#ifdef USE_ETHERNET_LAN8670
486 eth_type = "LAN8670";
487 break;
488#endif
489
490 default:
491 eth_type = "Unknown";
492 break;
493 }
494
495 ESP_LOGCONFIG(TAG,
496 "Ethernet:\n"
497 " Connected: %s",
498 YESNO(this->is_connected()));
499 this->dump_connect_params_();
500#ifdef USE_ETHERNET_SPI
501 ESP_LOGCONFIG(TAG,
502 " CLK Pin: %u\n"
503 " MISO Pin: %u\n"
504 " MOSI Pin: %u\n"
505 " CS Pin: %u",
506 this->clk_pin_, this->miso_pin_, this->mosi_pin_, this->cs_pin_);
507 const char *spi_interface = "spi3";
508 if (this->interface_ == SPI2_HOST) {
509 spi_interface = "spi2";
510 }
511 ESP_LOGCONFIG(TAG, " Interface: %s", spi_interface);
512#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
513 if (this->polling_interval_ != 0) {
514 ESP_LOGCONFIG(TAG, " Polling Interval: %" PRIu32 " ms", this->polling_interval_);
515 } else
516#endif
517 {
518 ESP_LOGCONFIG(TAG, " IRQ Pin: %d", this->interrupt_pin_);
519 }
520 ESP_LOGCONFIG(TAG,
521 " Reset Pin: %d\n"
522 " Clock Speed: %d MHz",
523 this->reset_pin_, this->clock_speed_ / 1000000);
524#else
525 if (this->power_pin_ != -1) {
526 ESP_LOGCONFIG(TAG, " Power Pin: %u", this->power_pin_);
527 }
528 ESP_LOGCONFIG(TAG,
529 " CLK Pin: %u\n"
530 " MDC Pin: %u\n"
531 " MDIO Pin: %u\n"
532 " PHY addr: %u",
533 this->clk_pin_, this->mdc_pin_, this->mdio_pin_, this->phy_addr_);
534#endif
535 ESP_LOGCONFIG(TAG, " Type: %s", eth_type);
536}
537
539 network::IPAddresses addresses;
540 if (!this->ethernet_initialized_)
541 return addresses; // all-zero IPs
542 esp_netif_ip_info_t ip;
543 esp_err_t err = esp_netif_get_ip_info(this->eth_netif_, &ip);
544 if (err != ESP_OK) {
545 ESP_LOGV(TAG, "esp_netif_get_ip_info failed: %s", esp_err_to_name(err));
546 // TODO: do something smarter
547 // return false;
548 } else {
549 addresses[0] = network::IPAddress(&ip.ip);
550 }
551#if USE_NETWORK_IPV6
552 struct esp_ip6_addr if_ip6s[CONFIG_LWIP_IPV6_NUM_ADDRESSES];
553 uint8_t count = 0;
554 count = esp_netif_get_all_ip6(this->eth_netif_, if_ip6s);
555 assert(count <= CONFIG_LWIP_IPV6_NUM_ADDRESSES);
556 assert(count < addresses.size());
557 for (int i = 0; i < count; i++) {
558 addresses[i + 1] = network::IPAddress(&if_ip6s[i]);
559 }
560#endif /* USE_NETWORK_IPV6 */
561
562 return addresses;
563}
564
567 const ip_addr_t *dns_ip = dns_getserver(num);
568 return dns_ip;
569}
570
571void EthernetComponent::eth_event_handler(void *arg, esp_event_base_t event_base, int32_t event, void *event_data) {
572 const char *event_name;
573
574 switch (event) {
575 case ETHERNET_EVENT_START:
576 event_name = "ETH started";
579 break;
580 case ETHERNET_EVENT_STOP:
581 event_name = "ETH stopped";
584 global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
585 break;
586 case ETHERNET_EVENT_CONNECTED:
587 event_name = "ETH connected";
588 // For static IP configurations, GOT_IP event may not fire, so notify IP listeners here
589#if defined(USE_ETHERNET_IP_STATE_LISTENERS) && defined(USE_ETHERNET_MANUAL_IP)
590 if (global_eth_component->manual_ip_.has_value()) {
592 }
593#endif
594 break;
595 case ETHERNET_EVENT_DISCONNECTED:
596 event_name = "ETH disconnected";
598 global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
599 break;
600 default:
601 return;
602 }
603
604 ESP_LOGV(TAG, "[Ethernet event] %s (num=%" PRId32 ")", event_name, event);
605}
606
607void EthernetComponent::got_ip_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id,
608 void *event_data) {
609 ip_event_got_ip_t *event = (ip_event_got_ip_t *) event_data;
610 const esp_netif_ip_info_t *ip_info = &event->ip_info;
611 ESP_LOGV(TAG, "[Ethernet event] ETH Got IP " IPSTR, IP2STR(&ip_info->ip));
613#if USE_NETWORK_IPV6 && (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
614 global_eth_component->connected_ = global_eth_component->ipv6_count_ >= USE_NETWORK_MIN_IPV6_ADDR_COUNT;
615 global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
616#else
618 global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
619#endif /* USE_NETWORK_IPV6 */
620#ifdef USE_ETHERNET_IP_STATE_LISTENERS
622#endif
623}
624
625#if USE_NETWORK_IPV6
626void EthernetComponent::got_ip6_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id,
627 void *event_data) {
628 ip_event_got_ip6_t *event = (ip_event_got_ip6_t *) event_data;
629 ESP_LOGV(TAG, "[Ethernet event] ETH Got IPv6: " IPV6STR, IPV62STR(event->ip6_info.ip));
631#if (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
633 global_eth_component->got_ipv4_address_ && (global_eth_component->ipv6_count_ >= USE_NETWORK_MIN_IPV6_ADDR_COUNT);
634 global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
635#else
637 global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
638#endif
639#ifdef USE_ETHERNET_IP_STATE_LISTENERS
641#endif
642}
643#endif /* USE_NETWORK_IPV6 */
644
646#if USE_NETWORK_IPV6
647 // Retry IPv6 link-local setup if it failed during initial connect
648 // This handles the case where min_ipv6_addr_count is NOT set (or is 0),
649 // allowing us to reach CONNECTED state with just IPv4.
650 // If IPv6 setup failed in start_connect_() because the interface wasn't ready:
651 // - Bootup timing issues (#10281)
652 // - Cable unplugged/network interruption (#10705)
653 // We can now retry since we're in CONNECTED state and the interface is definitely up.
654 if (!this->ipv6_setup_done_) {
655 esp_err_t err = esp_netif_create_ip6_linklocal(this->eth_netif_);
656 if (err == ESP_OK) {
657 ESP_LOGD(TAG, "IPv6 link-local address created (retry succeeded)");
658 }
659 // Always set the flag to prevent continuous retries
660 // If IPv6 setup fails here with the interface up and stable, it's
661 // likely a persistent issue (IPv6 disabled at router, hardware
662 // limitation, etc.) that won't be resolved by further retries.
663 // The device continues to work with IPv4.
664 this->ipv6_setup_done_ = true;
665 }
666#endif /* USE_NETWORK_IPV6 */
667}
668
671#if USE_NETWORK_IPV6
673 this->ipv6_setup_done_ = false;
674#endif /* USE_NETWORK_IPV6 */
675 this->connect_begin_ = millis();
676 this->status_set_warning(LOG_STR("waiting for IP configuration"));
677
678 esp_err_t err;
679 err = esp_netif_set_hostname(this->eth_netif_, App.get_name().c_str());
680 if (err != ERR_OK) {
681 ESP_LOGW(TAG, "esp_netif_set_hostname failed: %s", esp_err_to_name(err));
682 }
683
684 esp_netif_ip_info_t info;
685#ifdef USE_ETHERNET_MANUAL_IP
686 if (this->manual_ip_.has_value()) {
687 info.ip = this->manual_ip_->static_ip;
688 info.gw = this->manual_ip_->gateway;
689 info.netmask = this->manual_ip_->subnet;
690 } else
691#endif
692 {
693 info.ip.addr = 0;
694 info.gw.addr = 0;
695 info.netmask.addr = 0;
696 }
697
698 esp_netif_dhcp_status_t status = ESP_NETIF_DHCP_INIT;
699
700 err = esp_netif_dhcpc_get_status(this->eth_netif_, &status);
701 ESPHL_ERROR_CHECK(err, "DHCPC Get Status Failed!");
702
703 ESP_LOGV(TAG, "DHCP Client Status: %d", status);
704
705 err = esp_netif_dhcpc_stop(this->eth_netif_);
706 if (err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED) {
707 ESPHL_ERROR_CHECK(err, "DHCPC stop error");
708 }
709
710 err = esp_netif_set_ip_info(this->eth_netif_, &info);
711 ESPHL_ERROR_CHECK(err, "DHCPC set IP info error");
712
713#ifdef USE_ETHERNET_MANUAL_IP
714 if (this->manual_ip_.has_value()) {
716 if (this->manual_ip_->dns1.is_set()) {
717 ip_addr_t d;
718 d = this->manual_ip_->dns1;
719 dns_setserver(0, &d);
720 }
721 if (this->manual_ip_->dns2.is_set()) {
722 ip_addr_t d;
723 d = this->manual_ip_->dns2;
724 dns_setserver(1, &d);
725 }
726 } else
727#endif
728 {
729 err = esp_netif_dhcpc_start(this->eth_netif_);
730 if (err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED) {
731 ESPHL_ERROR_CHECK(err, "DHCPC start error");
732 }
733 }
734#if USE_NETWORK_IPV6
735 // Attempt to create IPv6 link-local address
736 // We MUST attempt this here, not just in finish_connect_(), because with
737 // min_ipv6_addr_count set, the component won't reach CONNECTED state without IPv6.
738 // However, this may fail with ESP_FAIL if the interface is not up yet:
739 // - At bootup when link isn't ready (#10281)
740 // - After disconnection/cable unplugged (#10705)
741 // We'll retry in finish_connect_() if it fails here.
742 err = esp_netif_create_ip6_linklocal(this->eth_netif_);
743 if (err != ESP_OK) {
744 if (err == ESP_ERR_ESP_NETIF_INVALID_PARAMS) {
745 // This is a programming error, not a transient failure
746 ESPHL_ERROR_CHECK(err, "esp_netif_create_ip6_linklocal invalid parameters");
747 } else {
748 // ESP_FAIL means the interface isn't up yet
749 // This is expected and non-fatal, happens in multiple scenarios:
750 // - During reconnection after network interruptions (#10705)
751 // - At bootup when the link isn't ready yet (#10281)
752 // We'll retry once we reach CONNECTED state and the interface is up
753 ESP_LOGW(TAG, "esp_netif_create_ip6_linklocal failed: %s", esp_err_to_name(err));
754 // Don't mark component as failed - this is a transient error
755 }
756 }
757#endif /* USE_NETWORK_IPV6 */
758
759 this->connect_begin_ = millis();
760 this->status_set_warning();
761}
762
764 if (!this->ethernet_initialized_) {
765 ESP_LOGCONFIG(TAG, " uninitialized/disabled");
766 return;
767 }
768 esp_netif_ip_info_t ip;
769 esp_netif_get_ip_info(this->eth_netif_, &ip);
770 const ip_addr_t *dns_ip1;
771 const ip_addr_t *dns_ip2;
772 {
774 dns_ip1 = dns_getserver(0);
775 dns_ip2 = dns_getserver(1);
776 }
777
778 // Use stack buffers for IP address formatting to avoid heap allocations
779 char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
780 char subnet_buf[network::IP_ADDRESS_BUFFER_SIZE];
781 char gateway_buf[network::IP_ADDRESS_BUFFER_SIZE];
782 char dns1_buf[network::IP_ADDRESS_BUFFER_SIZE];
783 char dns2_buf[network::IP_ADDRESS_BUFFER_SIZE];
784 char mac_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
785 ESP_LOGCONFIG(TAG,
786 " IP Address: %s\n"
787 " Hostname: '%s'\n"
788 " Subnet: %s\n"
789 " Gateway: %s\n"
790 " DNS1: %s\n"
791 " DNS2: %s\n"
792 " MAC Address: %s\n"
793 " Is Full Duplex: %s\n"
794 " Link Speed: %u",
795 network::IPAddress(&ip.ip).str_to(ip_buf), App.get_name().c_str(),
796 network::IPAddress(&ip.netmask).str_to(subnet_buf), network::IPAddress(&ip.gw).str_to(gateway_buf),
797 network::IPAddress(dns_ip1).str_to(dns1_buf), network::IPAddress(dns_ip2).str_to(dns2_buf),
798 this->get_eth_mac_address_pretty_into_buffer(mac_buf),
799 YESNO(this->get_duplex_mode() == ETH_DUPLEX_FULL), this->get_link_speed() == ETH_SPEED_100M ? 100 : 10);
800
801#if USE_NETWORK_IPV6
802 struct esp_ip6_addr if_ip6s[CONFIG_LWIP_IPV6_NUM_ADDRESSES];
803 uint8_t count = 0;
804 count = esp_netif_get_all_ip6(this->eth_netif_, if_ip6s);
805 assert(count <= CONFIG_LWIP_IPV6_NUM_ADDRESSES);
806 for (int i = 0; i < count; i++) {
807 ESP_LOGCONFIG(TAG, " IPv6: " IPV6STR, IPV62STR(if_ip6s[i]));
808 }
809#endif /* USE_NETWORK_IPV6 */
810}
811
812#ifdef USE_ETHERNET_SPI
813void EthernetComponent::set_clk_pin(uint8_t clk_pin) { this->clk_pin_ = clk_pin; }
814void EthernetComponent::set_miso_pin(uint8_t miso_pin) { this->miso_pin_ = miso_pin; }
815void EthernetComponent::set_mosi_pin(uint8_t mosi_pin) { this->mosi_pin_ = mosi_pin; }
816void EthernetComponent::set_cs_pin(uint8_t cs_pin) { this->cs_pin_ = cs_pin; }
817void EthernetComponent::set_interrupt_pin(uint8_t interrupt_pin) { this->interrupt_pin_ = interrupt_pin; }
818void EthernetComponent::set_reset_pin(uint8_t reset_pin) { this->reset_pin_ = reset_pin; }
819void EthernetComponent::set_clock_speed(int clock_speed) { this->clock_speed_ = clock_speed; }
820void EthernetComponent::set_interface(spi_host_device_t interface) { this->interface_ = interface; }
821#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
822void EthernetComponent::set_polling_interval(uint32_t polling_interval) { this->polling_interval_ = polling_interval; }
823#endif
824#else
825void EthernetComponent::set_phy_addr(uint8_t phy_addr) { this->phy_addr_ = phy_addr; }
826void EthernetComponent::set_power_pin(int power_pin) { this->power_pin_ = power_pin; }
827void EthernetComponent::set_mdc_pin(uint8_t mdc_pin) { this->mdc_pin_ = mdc_pin; }
828void EthernetComponent::set_mdio_pin(uint8_t mdio_pin) { this->mdio_pin_ = mdio_pin; }
829void EthernetComponent::set_clk_pin(uint8_t clk_pin) { this->clk_pin_ = clk_pin; }
830void EthernetComponent::set_clk_mode(emac_rmii_clock_mode_t clk_mode) { this->clk_mode_ = clk_mode; }
831void EthernetComponent::add_phy_register(PHYRegister register_value) { this->phy_registers_.push_back(register_value); }
832#endif
833
835 if (!this->ethernet_initialized_) {
836 // External callers (mdns, ethernet_info, etc.) may ask for the MAC before/regardless
837 // of whether ethernet is enabled. Use the configured MAC if set, else the system ETH MAC.
838 if (this->fixed_mac_.has_value()) {
839 memcpy(mac, this->fixed_mac_->data(), 6);
840 } else {
841 esp_read_mac(mac, ESP_MAC_ETH);
842 }
843 return;
844 }
845 esp_err_t err;
846 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_G_MAC_ADDR, mac);
847 ESPHL_ERROR_CHECK(err, "ETH_CMD_G_MAC error");
848}
849
850std::string EthernetComponent::get_eth_mac_address_pretty() {
851 char buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
852 return std::string(this->get_eth_mac_address_pretty_into_buffer(buf));
853}
854
856 std::span<char, MAC_ADDRESS_PRETTY_BUFFER_SIZE> buf) {
857 uint8_t mac[6];
859 format_mac_addr_upper(mac, buf.data());
860 return buf.data();
861}
862
864 if (!this->ethernet_initialized_)
865 return ETH_DUPLEX_HALF;
866 esp_err_t err;
867 eth_duplex_t duplex_mode;
868 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_G_DUPLEX_MODE, &duplex_mode);
869 ESPHL_ERROR_CHECK_RET(err, "ETH_CMD_G_DUPLEX_MODE error", ETH_DUPLEX_HALF);
870 return duplex_mode;
871}
872
874 if (!this->ethernet_initialized_)
875 return ETH_SPEED_10M;
876 esp_err_t err;
878 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_G_SPEED, &speed);
879 ESPHL_ERROR_CHECK_RET(err, "ETH_CMD_G_SPEED error", ETH_SPEED_10M);
880 return speed;
881}
882
884 ESP_LOGI(TAG, "Powering down ethernet PHY");
885 if (this->phy_ == nullptr) {
886 ESP_LOGE(TAG, "Ethernet PHY not assigned");
887 return false;
888 }
889 this->connected_ = false;
890 this->started_ = false;
891 // No need to enable_loop() here as this is only called during shutdown/reboot
892 if (this->phy_->pwrctl(this->phy_, false) != ESP_OK) {
893 ESP_LOGE(TAG, "Error powering down ethernet PHY");
894 return false;
895 }
896 return true;
897}
898
899#ifndef USE_ETHERNET_SPI
900
901#ifdef USE_ETHERNET_KSZ8081
902constexpr uint8_t KSZ80XX_PC2R_REG_ADDR = 0x1F;
903
905 esp_err_t err;
906
907 uint32_t phy_control_2;
908 err = mac->read_phy_reg(mac, this->phy_addr_, KSZ80XX_PC2R_REG_ADDR, &(phy_control_2));
909 ESPHL_ERROR_CHECK(err, "Read PHY Control 2 failed");
910#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
911 char hex_buf[format_hex_pretty_size(PHY_REG_SIZE)];
912#endif
913 ESP_LOGVV(TAG, "KSZ8081 PHY Control 2: %s", format_hex_pretty_to(hex_buf, (uint8_t *) &phy_control_2, PHY_REG_SIZE));
914
915 /*
916 * Bit 7 is `RMII Reference Clock Select`. Default is `0`.
917 * KSZ8081RNA:
918 * 0 - clock input to XI (Pin 8) is 25 MHz for RMII - 25 MHz clock mode.
919 * 1 - clock input to XI (Pin 8) is 50 MHz for RMII - 50 MHz clock mode.
920 * KSZ8081RND:
921 * 0 - clock input to XI (Pin 8) is 50 MHz for RMII - 50 MHz clock mode.
922 * 1 - clock input to XI (Pin 8) is 25 MHz (driven clock only, not a crystal) for RMII - 25 MHz clock mode.
923 */
924 if ((phy_control_2 & (1 << 7)) != (1 << 7)) {
925 phy_control_2 |= 1 << 7;
926 err = mac->write_phy_reg(mac, this->phy_addr_, KSZ80XX_PC2R_REG_ADDR, phy_control_2);
927 ESPHL_ERROR_CHECK(err, "Write PHY Control 2 failed");
928 err = mac->read_phy_reg(mac, this->phy_addr_, KSZ80XX_PC2R_REG_ADDR, &(phy_control_2));
929 ESPHL_ERROR_CHECK(err, "Read PHY Control 2 failed");
930 ESP_LOGVV(TAG, "KSZ8081 PHY Control 2: %s",
931 format_hex_pretty_to(hex_buf, (uint8_t *) &phy_control_2, PHY_REG_SIZE));
932 }
933}
934#endif // USE_ETHERNET_KSZ8081
935
936void EthernetComponent::write_phy_register_(esp_eth_mac_t *mac, PHYRegister register_data) {
937 esp_err_t err;
938
939#ifdef USE_ETHERNET_RTL8201
940 constexpr uint8_t eth_phy_psr_reg_addr = 0x1F;
941 if (this->type_ == ETHERNET_TYPE_RTL8201 && register_data.page) {
942 ESP_LOGD(TAG, "Select PHY Register Page: 0x%02" PRIX32, register_data.page);
943 err = mac->write_phy_reg(mac, this->phy_addr_, eth_phy_psr_reg_addr, register_data.page);
944 ESPHL_ERROR_CHECK(err, "Select PHY Register page failed");
945 }
946#endif
947
948 ESP_LOGD(TAG, "Writing PHY reg 0x%02" PRIX32 " = 0x%04" PRIX32, register_data.address, register_data.value);
949 err = mac->write_phy_reg(mac, this->phy_addr_, register_data.address, register_data.value);
950 ESPHL_ERROR_CHECK(err, "Writing PHY Register failed");
951
952#ifdef USE_ETHERNET_RTL8201
953 if (this->type_ == ETHERNET_TYPE_RTL8201 && register_data.page) {
954 ESP_LOGD(TAG, "Select PHY Register Page 0x00");
955 err = mac->write_phy_reg(mac, this->phy_addr_, eth_phy_psr_reg_addr, 0x0);
956 ESPHL_ERROR_CHECK(err, "Select PHY Register Page 0 failed");
957 }
958#endif
959}
960
961#endif
962
963} // namespace esphome::ethernet
964
965#endif // USE_ETHERNET && USE_ESP32
uint8_t status
Definition bl0942.h:8
const StringRef & get_name() const
Get the name of this Application set by pre_setup().
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void mark_failed()
Mark this component as failed.
void enable_loop_soon_any_context()
Thread and ISR-safe version of enable_loop() that can be called from any context.
void enable_loop()
Enable this component's loop.
Definition component.h:246
void disable_loop()
Disable this component's loop.
void status_clear_warning()
Definition component.h:289
Helper class to lock the lwIP TCPIP core when making lwIP API calls from non-TCPIP threads.
Definition helpers.h:1971
constexpr const char * c_str() const
Definition string_ref.h:73
void trigger(const Ts &...x) ESPHOME_ALWAYS_INLINE
Inform the parent automation that the event has triggered.
Definition automation.h:461
void set_interface(spi_host_device_t interface)
std::vector< PHYRegister > phy_registers_
static void got_ip_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
void set_polling_interval(uint32_t polling_interval)
void write_phy_register_(esp_eth_mac_t *mac, PHYRegister register_data)
Set arbitratry PHY registers from config.
static void got_ip6_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
void log_error_and_mark_failed_(esp_err_t err, const char *message)
network::IPAddress get_dns_address(uint8_t num)
void add_phy_register(PHYRegister register_value)
void ksz8081_set_clock_reference_(esp_eth_mac_t *mac)
Set RMII Reference Clock Select bit for KSZ8081.
static void eth_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
optional< std::array< uint8_t, 6 > > fixed_mac_
void set_clk_mode(emac_rmii_clock_mode_t clk_mode)
ESPDEPRECATED("Use get_eth_mac_address_pretty_into_buffer() instead. Removed in 2026.9.0", "2026.3.0") std const char * get_eth_mac_address_pretty_into_buffer(std::span< char, MAC_ADDRESS_PRETTY_BUFFER_SIZE > buf)
const LogString * message
Definition component.cpp:35
eth_esp32_emac_config_t eth_esp32_emac_default_config(void)
int speed
Definition fan.h:3
in_addr ip_addr_t
Definition ip_address.h:22
constexpr uint8_t KSZ80XX_PC2R_REG_ADDR
void install_w5500_async_spi(eth_w5500_config_t &config)
esp_eth_phy_t * esp_eth_phy_new_jl1101(const eth_phy_config_t *config)
EthernetComponent * global_eth_component
std::array< IPAddress, 5 > IPAddresses
Definition ip_address.h:223
char * format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator)
Format byte array as uppercase hex to buffer (base implementation).
Definition helpers.cpp:340
constexpr size_t format_hex_pretty_size(size_t byte_count)
Calculate buffer size needed for format_hex_pretty_to with separator: "XX:XX:...:XX\0".
Definition helpers.h:1386
void HOT delay(uint32_t ms)
Definition hal.cpp:85
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:28
Application App
Global storage of Application pointer - only one Application can exist.
char * format_mac_addr_upper(const uint8_t *mac, char *output)
Format MAC address as XX:XX:XX:XX:XX:XX (uppercase, colon separators)
Definition helpers.h:1453
static void uint32_t
uint8_t event_id
Definition tt21100.cpp:3
SemaphoreHandle_t lock