ESPHome 2026.1.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
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
190 this->phy_ = esp_eth_phy_new_lan87xx(&phy_config);
191 break;
192 }
194 this->phy_ = esp_eth_phy_new_rtl8201(&phy_config);
195 break;
196 }
198 this->phy_ = esp_eth_phy_new_dp83848(&phy_config);
199 break;
200 }
201 case ETHERNET_TYPE_IP101: {
202 this->phy_ = esp_eth_phy_new_ip101(&phy_config);
203 break;
204 }
206 this->phy_ = esp_eth_phy_new_jl1101(&phy_config);
207 break;
208 }
211 this->phy_ = esp_eth_phy_new_ksz80xx(&phy_config);
212 break;
213 }
214#ifdef USE_ETHERNET_LAN8670
216 this->phy_ = esp_eth_phy_new_lan867x(&phy_config);
217 break;
218 }
219#endif
220#endif
221#ifdef USE_ETHERNET_SPI
222#if CONFIG_ETH_SPI_ETHERNET_W5500
223 case ETHERNET_TYPE_W5500: {
224 mac = esp_eth_mac_new_w5500(&w5500_config, &mac_config);
225 this->phy_ = esp_eth_phy_new_w5500(&phy_config);
226 break;
227 }
228#endif
229#if CONFIG_ETH_SPI_ETHERNET_DM9051
231 mac = esp_eth_mac_new_dm9051(&dm9051_config, &mac_config);
232 this->phy_ = esp_eth_phy_new_dm9051(&phy_config);
233 break;
234 }
235#endif
236#endif
237 default: {
238 this->mark_failed();
239 return;
240 }
241 }
242
243 esp_eth_config_t eth_config = ETH_DEFAULT_CONFIG(mac, this->phy_);
244 this->eth_handle_ = nullptr;
245 err = esp_eth_driver_install(&eth_config, &this->eth_handle_);
246 ESPHL_ERROR_CHECK(err, "ETH driver install error");
247
248#ifndef USE_ETHERNET_SPI
249#ifdef USE_ETHERNET_KSZ8081
250 if (this->type_ == ETHERNET_TYPE_KSZ8081RNA && this->clk_mode_ == EMAC_CLK_OUT) {
251 // KSZ8081RNA default is incorrect. It expects a 25MHz clock instead of the 50MHz we provide.
253 }
254#endif // USE_ETHERNET_KSZ8081
255
256 for (const auto &phy_register : this->phy_registers_) {
257 this->write_phy_register_(mac, phy_register);
258 }
259#endif
260
261 // use ESP internal eth mac
262 uint8_t mac_addr[6];
263 if (this->fixed_mac_.has_value()) {
264 memcpy(mac_addr, this->fixed_mac_->data(), 6);
265 } else {
266 esp_read_mac(mac_addr, ESP_MAC_ETH);
267 }
268 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_S_MAC_ADDR, mac_addr);
269 ESPHL_ERROR_CHECK(err, "set mac address error");
270
271 /* attach Ethernet driver to TCP/IP stack */
272 err = esp_netif_attach(this->eth_netif_, esp_eth_new_netif_glue(this->eth_handle_));
273 ESPHL_ERROR_CHECK(err, "ETH netif attach error");
274
275 // Register user defined event handers
276 err = esp_event_handler_register(ETH_EVENT, ESP_EVENT_ANY_ID, &EthernetComponent::eth_event_handler, nullptr);
277 ESPHL_ERROR_CHECK(err, "ETH event handler register error");
278 err = esp_event_handler_register(IP_EVENT, IP_EVENT_ETH_GOT_IP, &EthernetComponent::got_ip_event_handler, nullptr);
279 ESPHL_ERROR_CHECK(err, "GOT IP event handler register error");
280#if USE_NETWORK_IPV6
281 err = esp_event_handler_register(IP_EVENT, IP_EVENT_GOT_IP6, &EthernetComponent::got_ip6_event_handler, nullptr);
282 ESPHL_ERROR_CHECK(err, "GOT IPv6 event handler register error");
283#endif /* USE_NETWORK_IPV6 */
284
285 /* start Ethernet driver state machine */
286 err = esp_eth_start(this->eth_handle_);
287 ESPHL_ERROR_CHECK(err, "ETH start error");
288}
289
291 const uint32_t now = App.get_loop_component_start_time();
292
293 switch (this->state_) {
295 if (this->started_) {
296 ESP_LOGI(TAG, "Starting connection");
298 this->start_connect_();
299 }
300 break;
302 if (!this->started_) {
303 ESP_LOGI(TAG, "Stopped connection");
305 } else if (this->connected_) {
306 // connection established
307 ESP_LOGI(TAG, "Connected");
309
310 this->dump_connect_params_();
311 this->status_clear_warning();
312 } else if (now - this->connect_begin_ > 15000) {
313 ESP_LOGW(TAG, "Connecting failed; reconnecting");
314 this->start_connect_();
315 }
316 break;
318 if (!this->started_) {
319 ESP_LOGI(TAG, "Stopped connection");
321 } else if (!this->connected_) {
322 ESP_LOGW(TAG, "Connection lost; reconnecting");
324 this->start_connect_();
325 } else {
326 this->finish_connect_();
327 // When connected and stable, disable the loop to save CPU cycles
328 this->disable_loop();
329 }
330 break;
331 }
332}
333
335 const char *eth_type;
336 switch (this->type_) {
338 eth_type = "LAN8720";
339 break;
340
342 eth_type = "RTL8201";
343 break;
344
346 eth_type = "DP83848";
347 break;
348
350 eth_type = "IP101";
351 break;
352
354 eth_type = "JL1101";
355 break;
356
358 eth_type = "KSZ8081";
359 break;
360
362 eth_type = "KSZ8081RNA";
363 break;
364
366 eth_type = "W5500";
367 break;
368
370 eth_type = "OPENETH";
371 break;
372
374 eth_type = "DM9051";
375 break;
376
377#ifdef USE_ETHERNET_LAN8670
379 eth_type = "LAN8670";
380 break;
381#endif
382
383 default:
384 eth_type = "Unknown";
385 break;
386 }
387
388 ESP_LOGCONFIG(TAG,
389 "Ethernet:\n"
390 " Connected: %s",
391 YESNO(this->is_connected()));
392 this->dump_connect_params_();
393#ifdef USE_ETHERNET_SPI
394 ESP_LOGCONFIG(TAG,
395 " CLK Pin: %u\n"
396 " MISO Pin: %u\n"
397 " MOSI Pin: %u\n"
398 " CS Pin: %u",
399 this->clk_pin_, this->miso_pin_, this->mosi_pin_, this->cs_pin_);
400#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
401 if (this->polling_interval_ != 0) {
402 ESP_LOGCONFIG(TAG, " Polling Interval: %lu ms", this->polling_interval_);
403 } else
404#endif
405 {
406 ESP_LOGCONFIG(TAG, " IRQ Pin: %d", this->interrupt_pin_);
407 }
408 ESP_LOGCONFIG(TAG,
409 " Reset Pin: %d\n"
410 " Clock Speed: %d MHz",
411 this->reset_pin_, this->clock_speed_ / 1000000);
412#else
413 if (this->power_pin_ != -1) {
414 ESP_LOGCONFIG(TAG, " Power Pin: %u", this->power_pin_);
415 }
416 ESP_LOGCONFIG(TAG,
417 " CLK Pin: %u\n"
418 " MDC Pin: %u\n"
419 " MDIO Pin: %u\n"
420 " PHY addr: %u",
421 this->clk_pin_, this->mdc_pin_, this->mdio_pin_, this->phy_addr_);
422#endif
423 ESP_LOGCONFIG(TAG, " Type: %s", eth_type);
424}
425
427
429 network::IPAddresses addresses;
430 esp_netif_ip_info_t ip;
431 esp_err_t err = esp_netif_get_ip_info(this->eth_netif_, &ip);
432 if (err != ESP_OK) {
433 ESP_LOGV(TAG, "esp_netif_get_ip_info failed: %s", esp_err_to_name(err));
434 // TODO: do something smarter
435 // return false;
436 } else {
437 addresses[0] = network::IPAddress(&ip.ip);
438 }
439#if USE_NETWORK_IPV6
440 struct esp_ip6_addr if_ip6s[CONFIG_LWIP_IPV6_NUM_ADDRESSES];
441 uint8_t count = 0;
442 count = esp_netif_get_all_ip6(this->eth_netif_, if_ip6s);
443 assert(count <= CONFIG_LWIP_IPV6_NUM_ADDRESSES);
444 for (int i = 0; i < count; i++) {
445 addresses[i + 1] = network::IPAddress(&if_ip6s[i]);
446 }
447#endif /* USE_NETWORK_IPV6 */
448
449 return addresses;
450}
451
453 LwIPLock lock;
454 const ip_addr_t *dns_ip = dns_getserver(num);
455 return dns_ip;
456}
457
458void EthernetComponent::eth_event_handler(void *arg, esp_event_base_t event_base, int32_t event, void *event_data) {
459 const char *event_name;
460
461 switch (event) {
462 case ETHERNET_EVENT_START:
463 event_name = "ETH started";
466 break;
467 case ETHERNET_EVENT_STOP:
468 event_name = "ETH stopped";
471 global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
472 break;
473 case ETHERNET_EVENT_CONNECTED:
474 event_name = "ETH connected";
475 break;
476 case ETHERNET_EVENT_DISCONNECTED:
477 event_name = "ETH disconnected";
479 global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
480 break;
481 default:
482 return;
483 }
484
485 ESP_LOGV(TAG, "[Ethernet event] %s (num=%" PRId32 ")", event_name, event);
486}
487
488void EthernetComponent::got_ip_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id,
489 void *event_data) {
490 ip_event_got_ip_t *event = (ip_event_got_ip_t *) event_data;
491 const esp_netif_ip_info_t *ip_info = &event->ip_info;
492 ESP_LOGV(TAG, "[Ethernet event] ETH Got IP " IPSTR, IP2STR(&ip_info->ip));
494#if USE_NETWORK_IPV6 && (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
495 global_eth_component->connected_ = global_eth_component->ipv6_count_ >= USE_NETWORK_MIN_IPV6_ADDR_COUNT;
496 global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
497#else
499 global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
500#endif /* USE_NETWORK_IPV6 */
501}
502
503#if USE_NETWORK_IPV6
504void EthernetComponent::got_ip6_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id,
505 void *event_data) {
506 ip_event_got_ip6_t *event = (ip_event_got_ip6_t *) event_data;
507 ESP_LOGV(TAG, "[Ethernet event] ETH Got IPv6: " IPV6STR, IPV62STR(event->ip6_info.ip));
509#if (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
511 global_eth_component->got_ipv4_address_ && (global_eth_component->ipv6_count_ >= USE_NETWORK_MIN_IPV6_ADDR_COUNT);
512 global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
513#else
515 global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
516#endif
517}
518#endif /* USE_NETWORK_IPV6 */
519
521#if USE_NETWORK_IPV6
522 // Retry IPv6 link-local setup if it failed during initial connect
523 // This handles the case where min_ipv6_addr_count is NOT set (or is 0),
524 // allowing us to reach CONNECTED state with just IPv4.
525 // If IPv6 setup failed in start_connect_() because the interface wasn't ready:
526 // - Bootup timing issues (#10281)
527 // - Cable unplugged/network interruption (#10705)
528 // We can now retry since we're in CONNECTED state and the interface is definitely up.
529 if (!this->ipv6_setup_done_) {
530 esp_err_t err = esp_netif_create_ip6_linklocal(this->eth_netif_);
531 if (err == ESP_OK) {
532 ESP_LOGD(TAG, "IPv6 link-local address created (retry succeeded)");
533 }
534 // Always set the flag to prevent continuous retries
535 // If IPv6 setup fails here with the interface up and stable, it's
536 // likely a persistent issue (IPv6 disabled at router, hardware
537 // limitation, etc.) that won't be resolved by further retries.
538 // The device continues to work with IPv4.
539 this->ipv6_setup_done_ = true;
540 }
541#endif /* USE_NETWORK_IPV6 */
542}
543
545 global_eth_component->got_ipv4_address_ = false;
546#if USE_NETWORK_IPV6
548 this->ipv6_setup_done_ = false;
549#endif /* USE_NETWORK_IPV6 */
550 this->connect_begin_ = millis();
551 this->status_set_warning(LOG_STR("waiting for IP configuration"));
552
553 esp_err_t err;
554 err = esp_netif_set_hostname(this->eth_netif_, App.get_name().c_str());
555 if (err != ERR_OK) {
556 ESP_LOGW(TAG, "esp_netif_set_hostname failed: %s", esp_err_to_name(err));
557 }
558
559 esp_netif_ip_info_t info;
560#ifdef USE_ETHERNET_MANUAL_IP
561 if (this->manual_ip_.has_value()) {
562 info.ip = this->manual_ip_->static_ip;
563 info.gw = this->manual_ip_->gateway;
564 info.netmask = this->manual_ip_->subnet;
565 } else
566#endif
567 {
568 info.ip.addr = 0;
569 info.gw.addr = 0;
570 info.netmask.addr = 0;
571 }
572
573 esp_netif_dhcp_status_t status = ESP_NETIF_DHCP_INIT;
574
575 err = esp_netif_dhcpc_get_status(this->eth_netif_, &status);
576 ESPHL_ERROR_CHECK(err, "DHCPC Get Status Failed!");
577
578 ESP_LOGV(TAG, "DHCP Client Status: %d", status);
579
580 err = esp_netif_dhcpc_stop(this->eth_netif_);
581 if (err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED) {
582 ESPHL_ERROR_CHECK(err, "DHCPC stop error");
583 }
584
585 err = esp_netif_set_ip_info(this->eth_netif_, &info);
586 ESPHL_ERROR_CHECK(err, "DHCPC set IP info error");
587
588#ifdef USE_ETHERNET_MANUAL_IP
589 if (this->manual_ip_.has_value()) {
590 LwIPLock lock;
591 if (this->manual_ip_->dns1.is_set()) {
592 ip_addr_t d;
593 d = this->manual_ip_->dns1;
594 dns_setserver(0, &d);
595 }
596 if (this->manual_ip_->dns2.is_set()) {
597 ip_addr_t d;
598 d = this->manual_ip_->dns2;
599 dns_setserver(1, &d);
600 }
601 } else
602#endif
603 {
604 err = esp_netif_dhcpc_start(this->eth_netif_);
605 if (err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED) {
606 ESPHL_ERROR_CHECK(err, "DHCPC start error");
607 }
608 }
609#if USE_NETWORK_IPV6
610 // Attempt to create IPv6 link-local address
611 // We MUST attempt this here, not just in finish_connect_(), because with
612 // min_ipv6_addr_count set, the component won't reach CONNECTED state without IPv6.
613 // However, this may fail with ESP_FAIL if the interface is not up yet:
614 // - At bootup when link isn't ready (#10281)
615 // - After disconnection/cable unplugged (#10705)
616 // We'll retry in finish_connect_() if it fails here.
617 err = esp_netif_create_ip6_linklocal(this->eth_netif_);
618 if (err != ESP_OK) {
619 if (err == ESP_ERR_ESP_NETIF_INVALID_PARAMS) {
620 // This is a programming error, not a transient failure
621 ESPHL_ERROR_CHECK(err, "esp_netif_create_ip6_linklocal invalid parameters");
622 } else {
623 // ESP_FAIL means the interface isn't up yet
624 // This is expected and non-fatal, happens in multiple scenarios:
625 // - During reconnection after network interruptions (#10705)
626 // - At bootup when the link isn't ready yet (#10281)
627 // We'll retry once we reach CONNECTED state and the interface is up
628 ESP_LOGW(TAG, "esp_netif_create_ip6_linklocal failed: %s", esp_err_to_name(err));
629 // Don't mark component as failed - this is a transient error
630 }
631 }
632#endif /* USE_NETWORK_IPV6 */
633
634 this->connect_begin_ = millis();
635 this->status_set_warning();
636}
637
639
641 esp_netif_ip_info_t ip;
642 esp_netif_get_ip_info(this->eth_netif_, &ip);
643 const ip_addr_t *dns_ip1;
644 const ip_addr_t *dns_ip2;
645 {
646 LwIPLock lock;
647 dns_ip1 = dns_getserver(0);
648 dns_ip2 = dns_getserver(1);
649 }
650
651 // Use stack buffers for IP address formatting to avoid heap allocations
652 char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
653 char subnet_buf[network::IP_ADDRESS_BUFFER_SIZE];
654 char gateway_buf[network::IP_ADDRESS_BUFFER_SIZE];
655 char dns1_buf[network::IP_ADDRESS_BUFFER_SIZE];
656 char dns2_buf[network::IP_ADDRESS_BUFFER_SIZE];
657 ESP_LOGCONFIG(TAG,
658 " IP Address: %s\n"
659 " Hostname: '%s'\n"
660 " Subnet: %s\n"
661 " Gateway: %s\n"
662 " DNS1: %s\n"
663 " DNS2: %s",
664 network::IPAddress(&ip.ip).str_to(ip_buf), App.get_name().c_str(),
665 network::IPAddress(&ip.netmask).str_to(subnet_buf), network::IPAddress(&ip.gw).str_to(gateway_buf),
666 network::IPAddress(dns_ip1).str_to(dns1_buf), network::IPAddress(dns_ip2).str_to(dns2_buf));
667
668#if USE_NETWORK_IPV6
669 struct esp_ip6_addr if_ip6s[CONFIG_LWIP_IPV6_NUM_ADDRESSES];
670 uint8_t count = 0;
671 count = esp_netif_get_all_ip6(this->eth_netif_, if_ip6s);
672 assert(count <= CONFIG_LWIP_IPV6_NUM_ADDRESSES);
673 for (int i = 0; i < count; i++) {
674 ESP_LOGCONFIG(TAG, " IPv6: " IPV6STR, IPV62STR(if_ip6s[i]));
675 }
676#endif /* USE_NETWORK_IPV6 */
677
678 char mac_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
679 ESP_LOGCONFIG(TAG,
680 " MAC Address: %s\n"
681 " Is Full Duplex: %s\n"
682 " Link Speed: %u",
684 YESNO(this->get_duplex_mode() == ETH_DUPLEX_FULL), this->get_link_speed() == ETH_SPEED_100M ? 100 : 10);
685}
686
687#ifdef USE_ETHERNET_SPI
688void EthernetComponent::set_clk_pin(uint8_t clk_pin) { this->clk_pin_ = clk_pin; }
689void EthernetComponent::set_miso_pin(uint8_t miso_pin) { this->miso_pin_ = miso_pin; }
690void EthernetComponent::set_mosi_pin(uint8_t mosi_pin) { this->mosi_pin_ = mosi_pin; }
691void EthernetComponent::set_cs_pin(uint8_t cs_pin) { this->cs_pin_ = cs_pin; }
692void EthernetComponent::set_interrupt_pin(uint8_t interrupt_pin) { this->interrupt_pin_ = interrupt_pin; }
693void EthernetComponent::set_reset_pin(uint8_t reset_pin) { this->reset_pin_ = reset_pin; }
694void EthernetComponent::set_clock_speed(int clock_speed) { this->clock_speed_ = clock_speed; }
695#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
696void EthernetComponent::set_polling_interval(uint32_t polling_interval) { this->polling_interval_ = polling_interval; }
697#endif
698#else
699void EthernetComponent::set_phy_addr(uint8_t phy_addr) { this->phy_addr_ = phy_addr; }
700void EthernetComponent::set_power_pin(int power_pin) { this->power_pin_ = power_pin; }
701void EthernetComponent::set_mdc_pin(uint8_t mdc_pin) { this->mdc_pin_ = mdc_pin; }
702void EthernetComponent::set_mdio_pin(uint8_t mdio_pin) { this->mdio_pin_ = mdio_pin; }
703void EthernetComponent::set_clk_pin(uint8_t clk_pin) { this->clk_pin_ = clk_pin; }
704void EthernetComponent::set_clk_mode(emac_rmii_clock_mode_t clk_mode) { this->clk_mode_ = clk_mode; }
705void EthernetComponent::add_phy_register(PHYRegister register_value) { this->phy_registers_.push_back(register_value); }
706#endif
708#ifdef USE_ETHERNET_MANUAL_IP
709void EthernetComponent::set_manual_ip(const ManualIP &manual_ip) { this->manual_ip_ = manual_ip; }
710#endif
711
712// set_use_address() is guaranteed to be called during component setup by Python code generation,
713// so use_address_ will always be valid when get_use_address() is called - no fallback needed.
714const char *EthernetComponent::get_use_address() const { return this->use_address_; }
715
716void EthernetComponent::set_use_address(const char *use_address) { this->use_address_ = use_address; }
717
719 esp_err_t err;
720 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_G_MAC_ADDR, mac);
721 ESPHL_ERROR_CHECK(err, "ETH_CMD_G_MAC error");
722}
723
725 char buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
726 return std::string(this->get_eth_mac_address_pretty_into_buffer(buf));
727}
728
730 std::span<char, MAC_ADDRESS_PRETTY_BUFFER_SIZE> buf) {
731 uint8_t mac[6];
733 format_mac_addr_upper(mac, buf.data());
734 return buf.data();
735}
736
738 esp_err_t err;
739 eth_duplex_t duplex_mode;
740 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_G_DUPLEX_MODE, &duplex_mode);
741 ESPHL_ERROR_CHECK_RET(err, "ETH_CMD_G_DUPLEX_MODE error", ETH_DUPLEX_HALF);
742 return duplex_mode;
743}
744
746 esp_err_t err;
747 eth_speed_t speed;
748 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_G_SPEED, &speed);
749 ESPHL_ERROR_CHECK_RET(err, "ETH_CMD_G_SPEED error", ETH_SPEED_10M);
750 return speed;
751}
752
754 ESP_LOGI(TAG, "Powering down ethernet PHY");
755 if (this->phy_ == nullptr) {
756 ESP_LOGE(TAG, "Ethernet PHY not assigned");
757 return false;
758 }
759 this->connected_ = false;
760 this->started_ = false;
761 // No need to enable_loop() here as this is only called during shutdown/reboot
762 if (this->phy_->pwrctl(this->phy_, false) != ESP_OK) {
763 ESP_LOGE(TAG, "Error powering down ethernet PHY");
764 return false;
765 }
766 return true;
767}
768
769#ifndef USE_ETHERNET_SPI
770
771#ifdef USE_ETHERNET_KSZ8081
772constexpr uint8_t KSZ80XX_PC2R_REG_ADDR = 0x1F;
773
775 esp_err_t err;
776
777 uint32_t phy_control_2;
778 err = mac->read_phy_reg(mac, this->phy_addr_, KSZ80XX_PC2R_REG_ADDR, &(phy_control_2));
779 ESPHL_ERROR_CHECK(err, "Read PHY Control 2 failed");
780#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
781 char hex_buf[format_hex_pretty_size(PHY_REG_SIZE)];
782#endif
783 ESP_LOGVV(TAG, "KSZ8081 PHY Control 2: %s", format_hex_pretty_to(hex_buf, (uint8_t *) &phy_control_2, PHY_REG_SIZE));
784
785 /*
786 * Bit 7 is `RMII Reference Clock Select`. Default is `0`.
787 * KSZ8081RNA:
788 * 0 - clock input to XI (Pin 8) is 25 MHz for RMII - 25 MHz clock mode.
789 * 1 - clock input to XI (Pin 8) is 50 MHz for RMII - 50 MHz clock mode.
790 * KSZ8081RND:
791 * 0 - clock input to XI (Pin 8) is 50 MHz for RMII - 50 MHz clock mode.
792 * 1 - clock input to XI (Pin 8) is 25 MHz (driven clock only, not a crystal) for RMII - 25 MHz clock mode.
793 */
794 if ((phy_control_2 & (1 << 7)) != (1 << 7)) {
795 phy_control_2 |= 1 << 7;
796 err = mac->write_phy_reg(mac, this->phy_addr_, KSZ80XX_PC2R_REG_ADDR, phy_control_2);
797 ESPHL_ERROR_CHECK(err, "Write PHY Control 2 failed");
798 err = mac->read_phy_reg(mac, this->phy_addr_, KSZ80XX_PC2R_REG_ADDR, &(phy_control_2));
799 ESPHL_ERROR_CHECK(err, "Read PHY Control 2 failed");
800 ESP_LOGVV(TAG, "KSZ8081 PHY Control 2: %s",
801 format_hex_pretty_to(hex_buf, (uint8_t *) &phy_control_2, PHY_REG_SIZE));
802 }
803}
804#endif // USE_ETHERNET_KSZ8081
805
806void EthernetComponent::write_phy_register_(esp_eth_mac_t *mac, PHYRegister register_data) {
807 esp_err_t err;
808 constexpr uint8_t eth_phy_psr_reg_addr = 0x1F;
809
810 if (this->type_ == ETHERNET_TYPE_RTL8201 && register_data.page) {
811 ESP_LOGD(TAG, "Select PHY Register Page: 0x%02" PRIX32, register_data.page);
812 err = mac->write_phy_reg(mac, this->phy_addr_, eth_phy_psr_reg_addr, register_data.page);
813 ESPHL_ERROR_CHECK(err, "Select PHY Register page failed");
814 }
815
816 ESP_LOGD(TAG, "Writing to PHY Register Address: 0x%02" PRIX32, register_data.address);
817 ESP_LOGD(TAG, "Writing to PHY Register Value: 0x%04" PRIX32, register_data.value);
818 err = mac->write_phy_reg(mac, this->phy_addr_, register_data.address, register_data.value);
819 ESPHL_ERROR_CHECK(err, "Writing PHY Register failed");
820
821 if (this->type_ == ETHERNET_TYPE_RTL8201 && register_data.page) {
822 ESP_LOGD(TAG, "Select PHY Register Page 0x00");
823 err = mac->write_phy_reg(mac, this->phy_addr_, eth_phy_psr_reg_addr, 0x0);
824 ESPHL_ERROR_CHECK(err, "Select PHY Register Page 0 failed");
825 }
826}
827
828#endif
829
830} // namespace ethernet
831} // namespace esphome
832
833#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:1196
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.
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:1
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:158
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
void 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:765
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:331
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:735
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 * str_to(char *buf) const
Write IP address to buffer. Buffer must be at least IP_ADDRESS_BUFFER_SIZE bytes.
Definition ip_address.h:57
uint8_t event_id
Definition tt21100.cpp:3