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