ESPHome 2026.4.0
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 auto host = this->interface_;
162
163 err = spi_bus_initialize(host, &buscfg, SPI_DMA_CH_AUTO);
164 ESPHL_ERROR_CHECK(err, "SPI bus initialize error");
165#endif
166
167 err = esp_netif_init();
168 ESPHL_ERROR_CHECK(err, "ETH netif init error");
169 err = esp_event_loop_create_default();
170 ESPHL_ERROR_CHECK(err, "ETH event loop error");
171
172 esp_netif_config_t cfg = ESP_NETIF_DEFAULT_ETH();
173 this->eth_netif_ = esp_netif_new(&cfg);
174
175 // Init MAC and PHY configs to default
176 eth_phy_config_t phy_config = ETH_PHY_DEFAULT_CONFIG();
177 eth_mac_config_t mac_config = ETH_MAC_DEFAULT_CONFIG();
178
179#ifdef USE_ETHERNET_SPI // Configure SPI interface and Ethernet driver for specific SPI module
180 spi_device_interface_config_t devcfg = {
181 .command_bits = 0,
182 .address_bits = 0,
183 .dummy_bits = 0,
184 .mode = 0,
185 .duty_cycle_pos = 0,
186 .cs_ena_pretrans = 0,
187 .cs_ena_posttrans = 0,
188 .clock_speed_hz = this->clock_speed_,
189 .input_delay_ns = 0,
190 .spics_io_num = this->cs_pin_,
191 .flags = 0,
192 .queue_size = 20,
193 .pre_cb = nullptr,
194 .post_cb = nullptr,
195 };
196
197#if defined(USE_ETHERNET_W5500)
198 eth_w5500_config_t w5500_config = ETH_W5500_DEFAULT_CONFIG(host, &devcfg);
199#elif defined(USE_ETHERNET_DM9051)
200 eth_dm9051_config_t dm9051_config = ETH_DM9051_DEFAULT_CONFIG(host, &devcfg);
201#elif defined(USE_ETHERNET_ENC28J60)
202 eth_enc28j60_config_t enc28j60_config = ETH_ENC28J60_DEFAULT_CONFIG(host, &devcfg);
203#endif
204
205#if defined(USE_ETHERNET_W5500)
206 w5500_config.int_gpio_num = this->interrupt_pin_;
207#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
208 w5500_config.poll_period_ms = this->polling_interval_;
209#endif
210#elif defined(USE_ETHERNET_DM9051)
211 dm9051_config.int_gpio_num = this->interrupt_pin_;
212#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
213 dm9051_config.poll_period_ms = this->polling_interval_;
214#endif
215#elif defined(USE_ETHERNET_ENC28J60)
216 enc28j60_config.int_gpio_num = this->interrupt_pin_;
217 // ENC28J60 does not support poll_period_ms
218#endif
219
220 phy_config.phy_addr = this->phy_addr_spi_;
221 phy_config.reset_gpio_num = this->reset_pin_;
222
223 esp_eth_mac_t *mac = nullptr;
224#elif defined(USE_ETHERNET_OPENETH)
225 esp_eth_mac_t *mac = esp_eth_mac_new_openeth(&mac_config);
226#else
227 phy_config.phy_addr = this->phy_addr_;
228 phy_config.reset_gpio_num = this->power_pin_;
229
230 eth_esp32_emac_config_t esp32_emac_config = eth_esp32_emac_default_config();
231#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 0)
232 esp32_emac_config.smi_gpio.mdc_num = this->mdc_pin_;
233 esp32_emac_config.smi_gpio.mdio_num = this->mdio_pin_;
234#else
235 esp32_emac_config.smi_mdc_gpio_num = this->mdc_pin_;
236 esp32_emac_config.smi_mdio_gpio_num = this->mdio_pin_;
237#endif
238 esp32_emac_config.clock_config.rmii.clock_mode = this->clk_mode_;
239 esp32_emac_config.clock_config.rmii.clock_gpio =
240 static_cast<decltype(esp32_emac_config.clock_config.rmii.clock_gpio)>(this->clk_pin_);
241
242 esp_eth_mac_t *mac = esp_eth_mac_new_esp32(&esp32_emac_config, &mac_config);
243#endif
244
245 switch (this->type_) {
246#ifdef USE_ETHERNET_OPENETH
248 phy_config.autonego_timeout_ms = 1000;
249#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
250 this->phy_ = esp_eth_phy_new_generic(&phy_config);
251#else
252 this->phy_ = esp_eth_phy_new_dp83848(&phy_config);
253#endif
254 break;
255 }
256#endif
257#if CONFIG_ETH_USE_ESP32_EMAC
258#ifdef USE_ETHERNET_LAN8720
260 this->phy_ = esp_eth_phy_new_lan87xx(&phy_config);
261 break;
262 }
263#endif
264#ifdef USE_ETHERNET_RTL8201
266 this->phy_ = esp_eth_phy_new_rtl8201(&phy_config);
267 break;
268 }
269#endif
270#ifdef USE_ETHERNET_DP83848
272 this->phy_ = esp_eth_phy_new_dp83848(&phy_config);
273 break;
274 }
275#endif
276#ifdef USE_ETHERNET_IP101
277 case ETHERNET_TYPE_IP101: {
278 this->phy_ = esp_eth_phy_new_ip101(&phy_config);
279 break;
280 }
281#endif
282#ifdef USE_ETHERNET_JL1101
284 // PlatformIO (pioarduino): builtin esp_eth_phy_new_jl1101() on all IDF versions
285 // Non-PlatformIO: custom ESPHome driver (esp_eth_phy_jl1101.c)
286 this->phy_ = esp_eth_phy_new_jl1101(&phy_config);
287 break;
288 }
289#endif
290#ifdef USE_ETHERNET_KSZ8081
293 this->phy_ = esp_eth_phy_new_ksz80xx(&phy_config);
294 break;
295 }
296#endif
297#ifdef USE_ETHERNET_LAN8670
299 this->phy_ = esp_eth_phy_new_lan867x(&phy_config);
300 break;
301 }
302#endif
303#endif
304#ifdef USE_ETHERNET_SPI
305#if defined(USE_ETHERNET_W5500)
306 case ETHERNET_TYPE_W5500: {
307 mac = esp_eth_mac_new_w5500(&w5500_config, &mac_config);
308 this->phy_ = esp_eth_phy_new_w5500(&phy_config);
309 break;
310 }
311#elif defined(USE_ETHERNET_DM9051)
313 mac = esp_eth_mac_new_dm9051(&dm9051_config, &mac_config);
314 this->phy_ = esp_eth_phy_new_dm9051(&phy_config);
315 break;
316 }
317#elif defined(USE_ETHERNET_ENC28J60)
319 mac = esp_eth_mac_new_enc28j60(&enc28j60_config, &mac_config);
320 this->phy_ = esp_eth_phy_new_enc28j60(&phy_config);
321 break;
322 }
323#endif
324#endif
325 default: {
326 this->mark_failed();
327 return;
328 }
329 }
330
331 esp_eth_config_t eth_config = ETH_DEFAULT_CONFIG(mac, this->phy_);
332 this->eth_handle_ = nullptr;
333 err = esp_eth_driver_install(&eth_config, &this->eth_handle_);
334 ESPHL_ERROR_CHECK(err, "ETH driver install error");
335
336#ifndef USE_ETHERNET_SPI
337#ifdef USE_ETHERNET_KSZ8081
338 if (this->type_ == ETHERNET_TYPE_KSZ8081RNA && this->clk_mode_ == EMAC_CLK_OUT) {
339 // KSZ8081RNA default is incorrect. It expects a 25MHz clock instead of the 50MHz we provide.
341 }
342#endif // USE_ETHERNET_KSZ8081
343
344 for (const auto &phy_register : this->phy_registers_) {
345 this->write_phy_register_(mac, phy_register);
346 }
347#endif
348
349 // use ESP internal eth mac
350 uint8_t mac_addr[6];
351 if (this->fixed_mac_.has_value()) {
352 memcpy(mac_addr, this->fixed_mac_->data(), 6);
353 } else {
354 esp_read_mac(mac_addr, ESP_MAC_ETH);
355 }
356 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_S_MAC_ADDR, mac_addr);
357 ESPHL_ERROR_CHECK(err, "set mac address error");
358
359 /* attach Ethernet driver to TCP/IP stack */
360 err = esp_netif_attach(this->eth_netif_, esp_eth_new_netif_glue(this->eth_handle_));
361 ESPHL_ERROR_CHECK(err, "ETH netif attach error");
362
363 // Register user defined event handers
364 err = esp_event_handler_register(ETH_EVENT, ESP_EVENT_ANY_ID, &EthernetComponent::eth_event_handler, nullptr);
365 ESPHL_ERROR_CHECK(err, "ETH event handler register error");
366 err = esp_event_handler_register(IP_EVENT, IP_EVENT_ETH_GOT_IP, &EthernetComponent::got_ip_event_handler, nullptr);
367 ESPHL_ERROR_CHECK(err, "GOT IP event handler register error");
368#if USE_NETWORK_IPV6
369 err = esp_event_handler_register(IP_EVENT, IP_EVENT_GOT_IP6, &EthernetComponent::got_ip6_event_handler, nullptr);
370 ESPHL_ERROR_CHECK(err, "GOT IPv6 event handler register error");
371#endif /* USE_NETWORK_IPV6 */
372
373 /* start Ethernet driver state machine */
374 err = esp_eth_start(this->eth_handle_);
375 ESPHL_ERROR_CHECK(err, "ETH start error");
376}
377
379 const char *eth_type;
380 switch (this->type_) {
381#ifdef USE_ETHERNET_LAN8720
383 eth_type = "LAN8720";
384 break;
385#endif
386#ifdef USE_ETHERNET_RTL8201
388 eth_type = "RTL8201";
389 break;
390#endif
391#ifdef USE_ETHERNET_DP83848
393 eth_type = "DP83848";
394 break;
395#endif
396#ifdef USE_ETHERNET_IP101
398 eth_type = "IP101";
399 break;
400#endif
401#ifdef USE_ETHERNET_JL1101
403 eth_type = "JL1101";
404 break;
405#endif
406#ifdef USE_ETHERNET_KSZ8081
408 eth_type = "KSZ8081";
409 break;
410
412 eth_type = "KSZ8081RNA";
413 break;
414#endif
415#if defined(USE_ETHERNET_W5500)
417 eth_type = "W5500";
418 break;
419#elif defined(USE_ETHERNET_DM9051)
421 eth_type = "DM9051";
422 break;
423#elif defined(USE_ETHERNET_ENC28J60)
425 eth_type = "ENC28J60";
426 break;
427#endif
428#ifdef USE_ETHERNET_OPENETH
430 eth_type = "OPENETH";
431 break;
432#endif
433#ifdef USE_ETHERNET_LAN8670
435 eth_type = "LAN8670";
436 break;
437#endif
438
439 default:
440 eth_type = "Unknown";
441 break;
442 }
443
444 ESP_LOGCONFIG(TAG,
445 "Ethernet:\n"
446 " Connected: %s",
447 YESNO(this->is_connected()));
448 this->dump_connect_params_();
449#ifdef USE_ETHERNET_SPI
450 ESP_LOGCONFIG(TAG,
451 " CLK Pin: %u\n"
452 " MISO Pin: %u\n"
453 " MOSI Pin: %u\n"
454 " CS Pin: %u",
455 this->clk_pin_, this->miso_pin_, this->mosi_pin_, this->cs_pin_);
456 const char *spi_interface = "spi3";
457 if (this->interface_ == SPI2_HOST) {
458 spi_interface = "spi2";
459 }
460 ESP_LOGCONFIG(TAG, " Interface: %s", spi_interface);
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; }
763void EthernetComponent::set_interface(spi_host_device_t interface) { this->interface_ = interface; }
764#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
765void EthernetComponent::set_polling_interval(uint32_t polling_interval) { this->polling_interval_ = polling_interval; }
766#endif
767#else
768void EthernetComponent::set_phy_addr(uint8_t phy_addr) { this->phy_addr_ = phy_addr; }
769void EthernetComponent::set_power_pin(int power_pin) { this->power_pin_ = power_pin; }
770void EthernetComponent::set_mdc_pin(uint8_t mdc_pin) { this->mdc_pin_ = mdc_pin; }
771void EthernetComponent::set_mdio_pin(uint8_t mdio_pin) { this->mdio_pin_ = mdio_pin; }
772void EthernetComponent::set_clk_pin(uint8_t clk_pin) { this->clk_pin_ = clk_pin; }
773void EthernetComponent::set_clk_mode(emac_rmii_clock_mode_t clk_mode) { this->clk_mode_ = clk_mode; }
774void EthernetComponent::add_phy_register(PHYRegister register_value) { this->phy_registers_.push_back(register_value); }
775#endif
776
778 esp_err_t err;
779 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_G_MAC_ADDR, mac);
780 ESPHL_ERROR_CHECK(err, "ETH_CMD_G_MAC error");
781}
782
783std::string EthernetComponent::get_eth_mac_address_pretty() {
784 char buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
785 return std::string(this->get_eth_mac_address_pretty_into_buffer(buf));
786}
787
789 std::span<char, MAC_ADDRESS_PRETTY_BUFFER_SIZE> buf) {
790 uint8_t mac[6];
792 format_mac_addr_upper(mac, buf.data());
793 return buf.data();
794}
795
797 esp_err_t err;
798 eth_duplex_t duplex_mode;
799 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_G_DUPLEX_MODE, &duplex_mode);
800 ESPHL_ERROR_CHECK_RET(err, "ETH_CMD_G_DUPLEX_MODE error", ETH_DUPLEX_HALF);
801 return duplex_mode;
802}
803
805 esp_err_t err;
807 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_G_SPEED, &speed);
808 ESPHL_ERROR_CHECK_RET(err, "ETH_CMD_G_SPEED error", ETH_SPEED_10M);
809 return speed;
810}
811
813 ESP_LOGI(TAG, "Powering down ethernet PHY");
814 if (this->phy_ == nullptr) {
815 ESP_LOGE(TAG, "Ethernet PHY not assigned");
816 return false;
817 }
818 this->connected_ = false;
819 this->started_ = false;
820 // No need to enable_loop() here as this is only called during shutdown/reboot
821 if (this->phy_->pwrctl(this->phy_, false) != ESP_OK) {
822 ESP_LOGE(TAG, "Error powering down ethernet PHY");
823 return false;
824 }
825 return true;
826}
827
828#ifndef USE_ETHERNET_SPI
829
830#ifdef USE_ETHERNET_KSZ8081
831constexpr uint8_t KSZ80XX_PC2R_REG_ADDR = 0x1F;
832
834 esp_err_t err;
835
836 uint32_t phy_control_2;
837 err = mac->read_phy_reg(mac, this->phy_addr_, KSZ80XX_PC2R_REG_ADDR, &(phy_control_2));
838 ESPHL_ERROR_CHECK(err, "Read PHY Control 2 failed");
839#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
840 char hex_buf[format_hex_pretty_size(PHY_REG_SIZE)];
841#endif
842 ESP_LOGVV(TAG, "KSZ8081 PHY Control 2: %s", format_hex_pretty_to(hex_buf, (uint8_t *) &phy_control_2, PHY_REG_SIZE));
843
844 /*
845 * Bit 7 is `RMII Reference Clock Select`. Default is `0`.
846 * KSZ8081RNA:
847 * 0 - clock input to XI (Pin 8) is 25 MHz for RMII - 25 MHz clock mode.
848 * 1 - clock input to XI (Pin 8) is 50 MHz for RMII - 50 MHz clock mode.
849 * KSZ8081RND:
850 * 0 - clock input to XI (Pin 8) is 50 MHz for RMII - 50 MHz clock mode.
851 * 1 - clock input to XI (Pin 8) is 25 MHz (driven clock only, not a crystal) for RMII - 25 MHz clock mode.
852 */
853 if ((phy_control_2 & (1 << 7)) != (1 << 7)) {
854 phy_control_2 |= 1 << 7;
855 err = mac->write_phy_reg(mac, this->phy_addr_, KSZ80XX_PC2R_REG_ADDR, phy_control_2);
856 ESPHL_ERROR_CHECK(err, "Write PHY Control 2 failed");
857 err = mac->read_phy_reg(mac, this->phy_addr_, KSZ80XX_PC2R_REG_ADDR, &(phy_control_2));
858 ESPHL_ERROR_CHECK(err, "Read PHY Control 2 failed");
859 ESP_LOGVV(TAG, "KSZ8081 PHY Control 2: %s",
860 format_hex_pretty_to(hex_buf, (uint8_t *) &phy_control_2, PHY_REG_SIZE));
861 }
862}
863#endif // USE_ETHERNET_KSZ8081
864
865void EthernetComponent::write_phy_register_(esp_eth_mac_t *mac, PHYRegister register_data) {
866 esp_err_t err;
867
868#ifdef USE_ETHERNET_RTL8201
869 constexpr uint8_t eth_phy_psr_reg_addr = 0x1F;
870 if (this->type_ == ETHERNET_TYPE_RTL8201 && register_data.page) {
871 ESP_LOGD(TAG, "Select PHY Register Page: 0x%02" PRIX32, register_data.page);
872 err = mac->write_phy_reg(mac, this->phy_addr_, eth_phy_psr_reg_addr, register_data.page);
873 ESPHL_ERROR_CHECK(err, "Select PHY Register page failed");
874 }
875#endif
876
877 ESP_LOGD(TAG, "Writing PHY reg 0x%02" PRIX32 " = 0x%04" PRIX32, register_data.address, register_data.value);
878 err = mac->write_phy_reg(mac, this->phy_addr_, register_data.address, register_data.value);
879 ESPHL_ERROR_CHECK(err, "Writing PHY Register failed");
880
881#ifdef USE_ETHERNET_RTL8201
882 if (this->type_ == ETHERNET_TYPE_RTL8201 && register_data.page) {
883 ESP_LOGD(TAG, "Select PHY Register Page 0x00");
884 err = mac->write_phy_reg(mac, this->phy_addr_, eth_phy_psr_reg_addr, 0x0);
885 ESPHL_ERROR_CHECK(err, "Select PHY Register Page 0 failed");
886 }
887#endif
888}
889
890#endif
891
892} // namespace esphome::ethernet
893
894#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:2108
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:470
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
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:392
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