ESPHome 2026.6.0-dev
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 esp_err_t err;
142
143#ifdef USE_ETHERNET_SPI
144 // Install GPIO ISR handler to be able to service SPI Eth modules interrupts
145 gpio_install_isr_service(0);
146
147 spi_bus_config_t buscfg = {
148 .mosi_io_num = this->mosi_pin_,
149 .miso_io_num = this->miso_pin_,
150 .sclk_io_num = this->clk_pin_,
151 .quadwp_io_num = -1,
152 .quadhd_io_num = -1,
153 .data4_io_num = -1,
154 .data5_io_num = -1,
155 .data6_io_num = -1,
156 .data7_io_num = -1,
157 .max_transfer_sz = 0,
158 .flags = 0,
159 .intr_flags = 0,
160 };
161
162 auto host = this->interface_;
163
164 err = spi_bus_initialize(host, &buscfg, SPI_DMA_CH_AUTO);
165 ESPHL_ERROR_CHECK(err, "SPI bus initialize error");
166#endif
167 // Network interface setup handled by network component
168
169 esp_netif_config_t cfg = ESP_NETIF_DEFAULT_ETH();
170 this->eth_netif_ = esp_netif_new(&cfg);
171
172 // Init MAC and PHY configs to default
173 eth_phy_config_t phy_config = ETH_PHY_DEFAULT_CONFIG();
174 eth_mac_config_t mac_config = ETH_MAC_DEFAULT_CONFIG();
175
176#ifdef USE_ETHERNET_SPI // Configure SPI interface and Ethernet driver for specific SPI module
177 spi_device_interface_config_t devcfg = {
178 .command_bits = 0,
179 .address_bits = 0,
180 .dummy_bits = 0,
181 .mode = 0,
182 .duty_cycle_pos = 0,
183 .cs_ena_pretrans = 0,
184 .cs_ena_posttrans = 0,
185 .clock_speed_hz = this->clock_speed_,
186 .input_delay_ns = 0,
187 .spics_io_num = this->cs_pin_,
188 .flags = 0,
189 .queue_size = 20,
190 .pre_cb = nullptr,
191 .post_cb = nullptr,
192 };
193
194#if defined(USE_ETHERNET_W5500)
195 eth_w5500_config_t w5500_config = ETH_W5500_DEFAULT_CONFIG(host, &devcfg);
196#elif defined(USE_ETHERNET_DM9051)
197 eth_dm9051_config_t dm9051_config = ETH_DM9051_DEFAULT_CONFIG(host, &devcfg);
198#elif defined(USE_ETHERNET_ENC28J60)
199 eth_enc28j60_config_t enc28j60_config = ETH_ENC28J60_DEFAULT_CONFIG(host, &devcfg);
200#endif
201
202#if defined(USE_ETHERNET_W5500)
203 w5500_config.int_gpio_num = this->interrupt_pin_;
204#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
205 w5500_config.poll_period_ms = this->polling_interval_;
206#endif
207 // Install the custom SPI driver that offloads the bulk RX/TX frame transfers off the busy-wait
208 // path. w5500_config (and the devcfg it references) outlives esp_eth_mac_new_w5500() below, which
209 // runs the driver's init().
210 install_w5500_async_spi(w5500_config);
211#elif defined(USE_ETHERNET_DM9051)
212 dm9051_config.int_gpio_num = this->interrupt_pin_;
213#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
214 dm9051_config.poll_period_ms = this->polling_interval_;
215#endif
216#elif defined(USE_ETHERNET_ENC28J60)
217 enc28j60_config.int_gpio_num = this->interrupt_pin_;
218 // ENC28J60 does not support poll_period_ms
219#endif
220
221 phy_config.phy_addr = this->phy_addr_spi_;
222 phy_config.reset_gpio_num = this->reset_pin_;
223
224 esp_eth_mac_t *mac = nullptr;
225#elif defined(USE_ETHERNET_OPENETH)
226 esp_eth_mac_t *mac = esp_eth_mac_new_openeth(&mac_config);
227#else
228 phy_config.phy_addr = this->phy_addr_;
229 phy_config.reset_gpio_num = this->power_pin_;
230
231 eth_esp32_emac_config_t esp32_emac_config = eth_esp32_emac_default_config();
232#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 0)
233 esp32_emac_config.smi_gpio.mdc_num = this->mdc_pin_;
234 esp32_emac_config.smi_gpio.mdio_num = this->mdio_pin_;
235#else
236 esp32_emac_config.smi_mdc_gpio_num = this->mdc_pin_;
237 esp32_emac_config.smi_mdio_gpio_num = this->mdio_pin_;
238#endif
239 esp32_emac_config.clock_config.rmii.clock_mode = this->clk_mode_;
240 esp32_emac_config.clock_config.rmii.clock_gpio =
241 static_cast<decltype(esp32_emac_config.clock_config.rmii.clock_gpio)>(this->clk_pin_);
242
243 esp_eth_mac_t *mac = esp_eth_mac_new_esp32(&esp32_emac_config, &mac_config);
244#endif
245
246 switch (this->type_) {
247#ifdef USE_ETHERNET_OPENETH
249 phy_config.autonego_timeout_ms = 1000;
250#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
251 this->phy_ = esp_eth_phy_new_generic(&phy_config);
252#else
253 this->phy_ = esp_eth_phy_new_dp83848(&phy_config);
254#endif
255 break;
256 }
257#endif
258#if CONFIG_ETH_USE_ESP32_EMAC
259#ifdef USE_ETHERNET_LAN8720
261 this->phy_ = esp_eth_phy_new_lan87xx(&phy_config);
262 break;
263 }
264#endif
265#ifdef USE_ETHERNET_RTL8201
267 this->phy_ = esp_eth_phy_new_rtl8201(&phy_config);
268 break;
269 }
270#endif
271#ifdef USE_ETHERNET_DP83848
273 this->phy_ = esp_eth_phy_new_dp83848(&phy_config);
274 break;
275 }
276#endif
277#ifdef USE_ETHERNET_IP101
278 case ETHERNET_TYPE_IP101: {
279 this->phy_ = esp_eth_phy_new_ip101(&phy_config);
280 break;
281 }
282#endif
283#ifdef USE_ETHERNET_JL1101
285 // PlatformIO (pioarduino): builtin esp_eth_phy_new_jl1101() on all IDF versions
286 // Non-PlatformIO: custom ESPHome driver (esp_eth_phy_jl1101.c)
287 this->phy_ = esp_eth_phy_new_jl1101(&phy_config);
288 break;
289 }
290#endif
291#ifdef USE_ETHERNET_KSZ8081
294 this->phy_ = esp_eth_phy_new_ksz80xx(&phy_config);
295 break;
296 }
297#endif
298#ifdef USE_ETHERNET_LAN8670
300 this->phy_ = esp_eth_phy_new_lan867x(&phy_config);
301 break;
302 }
303#endif
304#endif
305#ifdef USE_ETHERNET_SPI
306#if defined(USE_ETHERNET_W5500)
307 case ETHERNET_TYPE_W5500: {
308 mac = esp_eth_mac_new_w5500(&w5500_config, &mac_config);
309 this->phy_ = esp_eth_phy_new_w5500(&phy_config);
310 break;
311 }
312#elif defined(USE_ETHERNET_DM9051)
314 mac = esp_eth_mac_new_dm9051(&dm9051_config, &mac_config);
315 this->phy_ = esp_eth_phy_new_dm9051(&phy_config);
316 break;
317 }
318#elif defined(USE_ETHERNET_ENC28J60)
320 mac = esp_eth_mac_new_enc28j60(&enc28j60_config, &mac_config);
321 this->phy_ = esp_eth_phy_new_enc28j60(&phy_config);
322 break;
323 }
324#endif
325#endif
326 default: {
327 this->mark_failed();
328 return;
329 }
330 }
331
332 esp_eth_config_t eth_config = ETH_DEFAULT_CONFIG(mac, this->phy_);
333 this->eth_handle_ = nullptr;
334 err = esp_eth_driver_install(&eth_config, &this->eth_handle_);
335 ESPHL_ERROR_CHECK(err, "ETH driver install error");
336
337#ifndef USE_ETHERNET_SPI
338#ifdef USE_ETHERNET_KSZ8081
339 if (this->type_ == ETHERNET_TYPE_KSZ8081RNA && this->clk_mode_ == EMAC_CLK_OUT) {
340 // KSZ8081RNA default is incorrect. It expects a 25MHz clock instead of the 50MHz we provide.
342 }
343#endif // USE_ETHERNET_KSZ8081
344
345 for (const auto &phy_register : this->phy_registers_) {
346 this->write_phy_register_(mac, phy_register);
347 }
348#endif
349
350 // use ESP internal eth mac
351 uint8_t mac_addr[6];
352 if (this->fixed_mac_.has_value()) {
353 memcpy(mac_addr, this->fixed_mac_->data(), 6);
354 } else {
355 esp_read_mac(mac_addr, ESP_MAC_ETH);
356 }
357 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_S_MAC_ADDR, mac_addr);
358 ESPHL_ERROR_CHECK(err, "set mac address error");
359
360 /* attach Ethernet driver to TCP/IP stack */
361 err = esp_netif_attach(this->eth_netif_, esp_eth_new_netif_glue(this->eth_handle_));
362 ESPHL_ERROR_CHECK(err, "ETH netif attach error");
363
364 // Register user defined event handers
365 err = esp_event_handler_register(ETH_EVENT, ESP_EVENT_ANY_ID, &EthernetComponent::eth_event_handler, nullptr);
366 ESPHL_ERROR_CHECK(err, "ETH event handler register error");
367 err = esp_event_handler_register(IP_EVENT, IP_EVENT_ETH_GOT_IP, &EthernetComponent::got_ip_event_handler, nullptr);
368 ESPHL_ERROR_CHECK(err, "GOT IP event handler register error");
369#if USE_NETWORK_IPV6
370 err = esp_event_handler_register(IP_EVENT, IP_EVENT_GOT_IP6, &EthernetComponent::got_ip6_event_handler, nullptr);
371 ESPHL_ERROR_CHECK(err, "GOT IPv6 event handler register error");
372#endif /* USE_NETWORK_IPV6 */
373
374 /* start Ethernet driver state machine */
375 err = esp_eth_start(this->eth_handle_);
376 ESPHL_ERROR_CHECK(err, "ETH start error");
377}
378
380 const char *eth_type;
381 switch (this->type_) {
382#ifdef USE_ETHERNET_LAN8720
384 eth_type = "LAN8720";
385 break;
386#endif
387#ifdef USE_ETHERNET_RTL8201
389 eth_type = "RTL8201";
390 break;
391#endif
392#ifdef USE_ETHERNET_DP83848
394 eth_type = "DP83848";
395 break;
396#endif
397#ifdef USE_ETHERNET_IP101
399 eth_type = "IP101";
400 break;
401#endif
402#ifdef USE_ETHERNET_JL1101
404 eth_type = "JL1101";
405 break;
406#endif
407#ifdef USE_ETHERNET_KSZ8081
409 eth_type = "KSZ8081";
410 break;
411
413 eth_type = "KSZ8081RNA";
414 break;
415#endif
416#if defined(USE_ETHERNET_W5500)
418 eth_type = "W5500";
419 break;
420#elif defined(USE_ETHERNET_DM9051)
422 eth_type = "DM9051";
423 break;
424#elif defined(USE_ETHERNET_ENC28J60)
426 eth_type = "ENC28J60";
427 break;
428#endif
429#ifdef USE_ETHERNET_OPENETH
431 eth_type = "OPENETH";
432 break;
433#endif
434#ifdef USE_ETHERNET_LAN8670
436 eth_type = "LAN8670";
437 break;
438#endif
439
440 default:
441 eth_type = "Unknown";
442 break;
443 }
444
445 ESP_LOGCONFIG(TAG,
446 "Ethernet:\n"
447 " Connected: %s",
448 YESNO(this->is_connected()));
449 this->dump_connect_params_();
450#ifdef USE_ETHERNET_SPI
451 ESP_LOGCONFIG(TAG,
452 " CLK Pin: %u\n"
453 " MISO Pin: %u\n"
454 " MOSI Pin: %u\n"
455 " CS Pin: %u",
456 this->clk_pin_, this->miso_pin_, this->mosi_pin_, this->cs_pin_);
457 const char *spi_interface = "spi3";
458 if (this->interface_ == SPI2_HOST) {
459 spi_interface = "spi2";
460 }
461 ESP_LOGCONFIG(TAG, " Interface: %s", spi_interface);
462#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
463 if (this->polling_interval_ != 0) {
464 ESP_LOGCONFIG(TAG, " Polling Interval: %" PRIu32 " ms", this->polling_interval_);
465 } else
466#endif
467 {
468 ESP_LOGCONFIG(TAG, " IRQ Pin: %d", this->interrupt_pin_);
469 }
470 ESP_LOGCONFIG(TAG,
471 " Reset Pin: %d\n"
472 " Clock Speed: %d MHz",
473 this->reset_pin_, this->clock_speed_ / 1000000);
474#else
475 if (this->power_pin_ != -1) {
476 ESP_LOGCONFIG(TAG, " Power Pin: %u", this->power_pin_);
477 }
478 ESP_LOGCONFIG(TAG,
479 " CLK Pin: %u\n"
480 " MDC Pin: %u\n"
481 " MDIO Pin: %u\n"
482 " PHY addr: %u",
483 this->clk_pin_, this->mdc_pin_, this->mdio_pin_, this->phy_addr_);
484#endif
485 ESP_LOGCONFIG(TAG, " Type: %s", eth_type);
486}
487
489 network::IPAddresses addresses;
490 esp_netif_ip_info_t ip;
491 esp_err_t err = esp_netif_get_ip_info(this->eth_netif_, &ip);
492 if (err != ESP_OK) {
493 ESP_LOGV(TAG, "esp_netif_get_ip_info failed: %s", esp_err_to_name(err));
494 // TODO: do something smarter
495 // return false;
496 } else {
497 addresses[0] = network::IPAddress(&ip.ip);
498 }
499#if USE_NETWORK_IPV6
500 struct esp_ip6_addr if_ip6s[CONFIG_LWIP_IPV6_NUM_ADDRESSES];
501 uint8_t count = 0;
502 count = esp_netif_get_all_ip6(this->eth_netif_, if_ip6s);
503 assert(count <= CONFIG_LWIP_IPV6_NUM_ADDRESSES);
504 assert(count < addresses.size());
505 for (int i = 0; i < count; i++) {
506 addresses[i + 1] = network::IPAddress(&if_ip6s[i]);
507 }
508#endif /* USE_NETWORK_IPV6 */
509
510 return addresses;
511}
512
515 const ip_addr_t *dns_ip = dns_getserver(num);
516 return dns_ip;
517}
518
519void EthernetComponent::eth_event_handler(void *arg, esp_event_base_t event_base, int32_t event, void *event_data) {
520 const char *event_name;
521
522 switch (event) {
523 case ETHERNET_EVENT_START:
524 event_name = "ETH started";
527 break;
528 case ETHERNET_EVENT_STOP:
529 event_name = "ETH stopped";
532 global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
533 break;
534 case ETHERNET_EVENT_CONNECTED:
535 event_name = "ETH connected";
536 // For static IP configurations, GOT_IP event may not fire, so notify IP listeners here
537#if defined(USE_ETHERNET_IP_STATE_LISTENERS) && defined(USE_ETHERNET_MANUAL_IP)
538 if (global_eth_component->manual_ip_.has_value()) {
540 }
541#endif
542 break;
543 case ETHERNET_EVENT_DISCONNECTED:
544 event_name = "ETH disconnected";
546 global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
547 break;
548 default:
549 return;
550 }
551
552 ESP_LOGV(TAG, "[Ethernet event] %s (num=%" PRId32 ")", event_name, event);
553}
554
555void EthernetComponent::got_ip_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id,
556 void *event_data) {
557 ip_event_got_ip_t *event = (ip_event_got_ip_t *) event_data;
558 const esp_netif_ip_info_t *ip_info = &event->ip_info;
559 ESP_LOGV(TAG, "[Ethernet event] ETH Got IP " IPSTR, IP2STR(&ip_info->ip));
561#if USE_NETWORK_IPV6 && (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
562 global_eth_component->connected_ = global_eth_component->ipv6_count_ >= USE_NETWORK_MIN_IPV6_ADDR_COUNT;
563 global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
564#else
566 global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
567#endif /* USE_NETWORK_IPV6 */
568#ifdef USE_ETHERNET_IP_STATE_LISTENERS
570#endif
571}
572
573#if USE_NETWORK_IPV6
574void EthernetComponent::got_ip6_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id,
575 void *event_data) {
576 ip_event_got_ip6_t *event = (ip_event_got_ip6_t *) event_data;
577 ESP_LOGV(TAG, "[Ethernet event] ETH Got IPv6: " IPV6STR, IPV62STR(event->ip6_info.ip));
579#if (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
581 global_eth_component->got_ipv4_address_ && (global_eth_component->ipv6_count_ >= USE_NETWORK_MIN_IPV6_ADDR_COUNT);
582 global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
583#else
585 global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
586#endif
587#ifdef USE_ETHERNET_IP_STATE_LISTENERS
589#endif
590}
591#endif /* USE_NETWORK_IPV6 */
592
594#if USE_NETWORK_IPV6
595 // Retry IPv6 link-local setup if it failed during initial connect
596 // This handles the case where min_ipv6_addr_count is NOT set (or is 0),
597 // allowing us to reach CONNECTED state with just IPv4.
598 // If IPv6 setup failed in start_connect_() because the interface wasn't ready:
599 // - Bootup timing issues (#10281)
600 // - Cable unplugged/network interruption (#10705)
601 // We can now retry since we're in CONNECTED state and the interface is definitely up.
602 if (!this->ipv6_setup_done_) {
603 esp_err_t err = esp_netif_create_ip6_linklocal(this->eth_netif_);
604 if (err == ESP_OK) {
605 ESP_LOGD(TAG, "IPv6 link-local address created (retry succeeded)");
606 }
607 // Always set the flag to prevent continuous retries
608 // If IPv6 setup fails here with the interface up and stable, it's
609 // likely a persistent issue (IPv6 disabled at router, hardware
610 // limitation, etc.) that won't be resolved by further retries.
611 // The device continues to work with IPv4.
612 this->ipv6_setup_done_ = true;
613 }
614#endif /* USE_NETWORK_IPV6 */
615}
616
619#if USE_NETWORK_IPV6
621 this->ipv6_setup_done_ = false;
622#endif /* USE_NETWORK_IPV6 */
623 this->connect_begin_ = millis();
624 this->status_set_warning(LOG_STR("waiting for IP configuration"));
625
626 esp_err_t err;
627 err = esp_netif_set_hostname(this->eth_netif_, App.get_name().c_str());
628 if (err != ERR_OK) {
629 ESP_LOGW(TAG, "esp_netif_set_hostname failed: %s", esp_err_to_name(err));
630 }
631
632 esp_netif_ip_info_t info;
633#ifdef USE_ETHERNET_MANUAL_IP
634 if (this->manual_ip_.has_value()) {
635 info.ip = this->manual_ip_->static_ip;
636 info.gw = this->manual_ip_->gateway;
637 info.netmask = this->manual_ip_->subnet;
638 } else
639#endif
640 {
641 info.ip.addr = 0;
642 info.gw.addr = 0;
643 info.netmask.addr = 0;
644 }
645
646 esp_netif_dhcp_status_t status = ESP_NETIF_DHCP_INIT;
647
648 err = esp_netif_dhcpc_get_status(this->eth_netif_, &status);
649 ESPHL_ERROR_CHECK(err, "DHCPC Get Status Failed!");
650
651 ESP_LOGV(TAG, "DHCP Client Status: %d", status);
652
653 err = esp_netif_dhcpc_stop(this->eth_netif_);
654 if (err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED) {
655 ESPHL_ERROR_CHECK(err, "DHCPC stop error");
656 }
657
658 err = esp_netif_set_ip_info(this->eth_netif_, &info);
659 ESPHL_ERROR_CHECK(err, "DHCPC set IP info error");
660
661#ifdef USE_ETHERNET_MANUAL_IP
662 if (this->manual_ip_.has_value()) {
664 if (this->manual_ip_->dns1.is_set()) {
665 ip_addr_t d;
666 d = this->manual_ip_->dns1;
667 dns_setserver(0, &d);
668 }
669 if (this->manual_ip_->dns2.is_set()) {
670 ip_addr_t d;
671 d = this->manual_ip_->dns2;
672 dns_setserver(1, &d);
673 }
674 } else
675#endif
676 {
677 err = esp_netif_dhcpc_start(this->eth_netif_);
678 if (err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED) {
679 ESPHL_ERROR_CHECK(err, "DHCPC start error");
680 }
681 }
682#if USE_NETWORK_IPV6
683 // Attempt to create IPv6 link-local address
684 // We MUST attempt this here, not just in finish_connect_(), because with
685 // min_ipv6_addr_count set, the component won't reach CONNECTED state without IPv6.
686 // However, this may fail with ESP_FAIL if the interface is not up yet:
687 // - At bootup when link isn't ready (#10281)
688 // - After disconnection/cable unplugged (#10705)
689 // We'll retry in finish_connect_() if it fails here.
690 err = esp_netif_create_ip6_linklocal(this->eth_netif_);
691 if (err != ESP_OK) {
692 if (err == ESP_ERR_ESP_NETIF_INVALID_PARAMS) {
693 // This is a programming error, not a transient failure
694 ESPHL_ERROR_CHECK(err, "esp_netif_create_ip6_linklocal invalid parameters");
695 } else {
696 // ESP_FAIL means the interface isn't up yet
697 // This is expected and non-fatal, happens in multiple scenarios:
698 // - During reconnection after network interruptions (#10705)
699 // - At bootup when the link isn't ready yet (#10281)
700 // We'll retry once we reach CONNECTED state and the interface is up
701 ESP_LOGW(TAG, "esp_netif_create_ip6_linklocal failed: %s", esp_err_to_name(err));
702 // Don't mark component as failed - this is a transient error
703 }
704 }
705#endif /* USE_NETWORK_IPV6 */
706
707 this->connect_begin_ = millis();
708 this->status_set_warning();
709}
710
712 esp_netif_ip_info_t ip;
713 esp_netif_get_ip_info(this->eth_netif_, &ip);
714 const ip_addr_t *dns_ip1;
715 const ip_addr_t *dns_ip2;
716 {
718 dns_ip1 = dns_getserver(0);
719 dns_ip2 = dns_getserver(1);
720 }
721
722 // Use stack buffers for IP address formatting to avoid heap allocations
723 char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
724 char subnet_buf[network::IP_ADDRESS_BUFFER_SIZE];
725 char gateway_buf[network::IP_ADDRESS_BUFFER_SIZE];
726 char dns1_buf[network::IP_ADDRESS_BUFFER_SIZE];
727 char dns2_buf[network::IP_ADDRESS_BUFFER_SIZE];
728 char mac_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
729 ESP_LOGCONFIG(TAG,
730 " IP Address: %s\n"
731 " Hostname: '%s'\n"
732 " Subnet: %s\n"
733 " Gateway: %s\n"
734 " DNS1: %s\n"
735 " DNS2: %s\n"
736 " MAC Address: %s\n"
737 " Is Full Duplex: %s\n"
738 " Link Speed: %u",
739 network::IPAddress(&ip.ip).str_to(ip_buf), App.get_name().c_str(),
740 network::IPAddress(&ip.netmask).str_to(subnet_buf), network::IPAddress(&ip.gw).str_to(gateway_buf),
741 network::IPAddress(dns_ip1).str_to(dns1_buf), network::IPAddress(dns_ip2).str_to(dns2_buf),
742 this->get_eth_mac_address_pretty_into_buffer(mac_buf),
743 YESNO(this->get_duplex_mode() == ETH_DUPLEX_FULL), this->get_link_speed() == ETH_SPEED_100M ? 100 : 10);
744
745#if USE_NETWORK_IPV6
746 struct esp_ip6_addr if_ip6s[CONFIG_LWIP_IPV6_NUM_ADDRESSES];
747 uint8_t count = 0;
748 count = esp_netif_get_all_ip6(this->eth_netif_, if_ip6s);
749 assert(count <= CONFIG_LWIP_IPV6_NUM_ADDRESSES);
750 for (int i = 0; i < count; i++) {
751 ESP_LOGCONFIG(TAG, " IPv6: " IPV6STR, IPV62STR(if_ip6s[i]));
752 }
753#endif /* USE_NETWORK_IPV6 */
754}
755
756#ifdef USE_ETHERNET_SPI
757void EthernetComponent::set_clk_pin(uint8_t clk_pin) { this->clk_pin_ = clk_pin; }
758void EthernetComponent::set_miso_pin(uint8_t miso_pin) { this->miso_pin_ = miso_pin; }
759void EthernetComponent::set_mosi_pin(uint8_t mosi_pin) { this->mosi_pin_ = mosi_pin; }
760void EthernetComponent::set_cs_pin(uint8_t cs_pin) { this->cs_pin_ = cs_pin; }
761void EthernetComponent::set_interrupt_pin(uint8_t interrupt_pin) { this->interrupt_pin_ = interrupt_pin; }
762void EthernetComponent::set_reset_pin(uint8_t reset_pin) { this->reset_pin_ = reset_pin; }
763void EthernetComponent::set_clock_speed(int clock_speed) { this->clock_speed_ = clock_speed; }
764void EthernetComponent::set_interface(spi_host_device_t interface) { this->interface_ = interface; }
765#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
766void EthernetComponent::set_polling_interval(uint32_t polling_interval) { this->polling_interval_ = polling_interval; }
767#endif
768#else
769void EthernetComponent::set_phy_addr(uint8_t phy_addr) { this->phy_addr_ = phy_addr; }
770void EthernetComponent::set_power_pin(int power_pin) { this->power_pin_ = power_pin; }
771void EthernetComponent::set_mdc_pin(uint8_t mdc_pin) { this->mdc_pin_ = mdc_pin; }
772void EthernetComponent::set_mdio_pin(uint8_t mdio_pin) { this->mdio_pin_ = mdio_pin; }
773void EthernetComponent::set_clk_pin(uint8_t clk_pin) { this->clk_pin_ = clk_pin; }
774void EthernetComponent::set_clk_mode(emac_rmii_clock_mode_t clk_mode) { this->clk_mode_ = clk_mode; }
775void EthernetComponent::add_phy_register(PHYRegister register_value) { this->phy_registers_.push_back(register_value); }
776#endif
777
779 esp_err_t err;
780 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_G_MAC_ADDR, mac);
781 ESPHL_ERROR_CHECK(err, "ETH_CMD_G_MAC error");
782}
783
784std::string EthernetComponent::get_eth_mac_address_pretty() {
785 char buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
786 return std::string(this->get_eth_mac_address_pretty_into_buffer(buf));
787}
788
790 std::span<char, MAC_ADDRESS_PRETTY_BUFFER_SIZE> buf) {
791 uint8_t mac[6];
793 format_mac_addr_upper(mac, buf.data());
794 return buf.data();
795}
796
798 esp_err_t err;
799 eth_duplex_t duplex_mode;
800 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_G_DUPLEX_MODE, &duplex_mode);
801 ESPHL_ERROR_CHECK_RET(err, "ETH_CMD_G_DUPLEX_MODE error", ETH_DUPLEX_HALF);
802 return duplex_mode;
803}
804
806 esp_err_t err;
808 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_G_SPEED, &speed);
809 ESPHL_ERROR_CHECK_RET(err, "ETH_CMD_G_SPEED error", ETH_SPEED_10M);
810 return speed;
811}
812
814 ESP_LOGI(TAG, "Powering down ethernet PHY");
815 if (this->phy_ == nullptr) {
816 ESP_LOGE(TAG, "Ethernet PHY not assigned");
817 return false;
818 }
819 this->connected_ = false;
820 this->started_ = false;
821 // No need to enable_loop() here as this is only called during shutdown/reboot
822 if (this->phy_->pwrctl(this->phy_, false) != ESP_OK) {
823 ESP_LOGE(TAG, "Error powering down ethernet PHY");
824 return false;
825 }
826 return true;
827}
828
829#ifndef USE_ETHERNET_SPI
830
831#ifdef USE_ETHERNET_KSZ8081
832constexpr uint8_t KSZ80XX_PC2R_REG_ADDR = 0x1F;
833
835 esp_err_t err;
836
837 uint32_t phy_control_2;
838 err = mac->read_phy_reg(mac, this->phy_addr_, KSZ80XX_PC2R_REG_ADDR, &(phy_control_2));
839 ESPHL_ERROR_CHECK(err, "Read PHY Control 2 failed");
840#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
841 char hex_buf[format_hex_pretty_size(PHY_REG_SIZE)];
842#endif
843 ESP_LOGVV(TAG, "KSZ8081 PHY Control 2: %s", format_hex_pretty_to(hex_buf, (uint8_t *) &phy_control_2, PHY_REG_SIZE));
844
845 /*
846 * Bit 7 is `RMII Reference Clock Select`. Default is `0`.
847 * KSZ8081RNA:
848 * 0 - clock input to XI (Pin 8) is 25 MHz for RMII - 25 MHz clock mode.
849 * 1 - clock input to XI (Pin 8) is 50 MHz for RMII - 50 MHz clock mode.
850 * KSZ8081RND:
851 * 0 - clock input to XI (Pin 8) is 50 MHz for RMII - 50 MHz clock mode.
852 * 1 - clock input to XI (Pin 8) is 25 MHz (driven clock only, not a crystal) for RMII - 25 MHz clock mode.
853 */
854 if ((phy_control_2 & (1 << 7)) != (1 << 7)) {
855 phy_control_2 |= 1 << 7;
856 err = mac->write_phy_reg(mac, this->phy_addr_, KSZ80XX_PC2R_REG_ADDR, phy_control_2);
857 ESPHL_ERROR_CHECK(err, "Write PHY Control 2 failed");
858 err = mac->read_phy_reg(mac, this->phy_addr_, KSZ80XX_PC2R_REG_ADDR, &(phy_control_2));
859 ESPHL_ERROR_CHECK(err, "Read PHY Control 2 failed");
860 ESP_LOGVV(TAG, "KSZ8081 PHY Control 2: %s",
861 format_hex_pretty_to(hex_buf, (uint8_t *) &phy_control_2, PHY_REG_SIZE));
862 }
863}
864#endif // USE_ETHERNET_KSZ8081
865
866void EthernetComponent::write_phy_register_(esp_eth_mac_t *mac, PHYRegister register_data) {
867 esp_err_t err;
868
869#ifdef USE_ETHERNET_RTL8201
870 constexpr uint8_t eth_phy_psr_reg_addr = 0x1F;
871 if (this->type_ == ETHERNET_TYPE_RTL8201 && register_data.page) {
872 ESP_LOGD(TAG, "Select PHY Register Page: 0x%02" PRIX32, register_data.page);
873 err = mac->write_phy_reg(mac, this->phy_addr_, eth_phy_psr_reg_addr, register_data.page);
874 ESPHL_ERROR_CHECK(err, "Select PHY Register page failed");
875 }
876#endif
877
878 ESP_LOGD(TAG, "Writing PHY reg 0x%02" PRIX32 " = 0x%04" PRIX32, register_data.address, register_data.value);
879 err = mac->write_phy_reg(mac, this->phy_addr_, register_data.address, register_data.value);
880 ESPHL_ERROR_CHECK(err, "Writing PHY Register failed");
881
882#ifdef USE_ETHERNET_RTL8201
883 if (this->type_ == ETHERNET_TYPE_RTL8201 && register_data.page) {
884 ESP_LOGD(TAG, "Select PHY Register Page 0x00");
885 err = mac->write_phy_reg(mac, this->phy_addr_, eth_phy_psr_reg_addr, 0x0);
886 ESPHL_ERROR_CHECK(err, "Select PHY Register Page 0 failed");
887 }
888#endif
889}
890
891#endif
892
893} // namespace esphome::ethernet
894
895#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 disable_loop()
Disable this component's loop.
void status_clear_warning()
Definition component.h:306
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:482
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 char * 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:187
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:341
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