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