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