ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
ethernet_component_esp32.cpp
Go to the documentation of this file.
2
3#if defined(USE_ETHERNET) && defined(USE_ESP32)
4
8#include "esphome/core/log.h"
9#include "w5500_custom_spi.h"
10
11#include <lwip/dns.h>
12#include <cinttypes>
13#include "esp_event.h"
14#if USE_NETWORK_IPV6
15#include <esp_netif_net_stack.h>
16#include <lwip/netif.h>
17#endif
18#ifdef USE_PSRAM
19#include <esp_psram.h>
20#endif
21
22// IDF 6.0 moved per-chip PHY/MAC drivers to the Espressif Component Registry;
23// they are no longer included via esp_eth.h and need explicit includes.
24// On IDF 5.x these headers don't exist as standalone files.
25#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
26#ifdef USE_ETHERNET_LAN8720
27#include "esp_eth_phy_lan87xx.h"
28#endif
29#ifdef USE_ETHERNET_RTL8201
30#include "esp_eth_phy_rtl8201.h"
31#endif
32#ifdef USE_ETHERNET_DP83848
33#include "esp_eth_phy_dp83848.h"
34#endif
35#ifdef USE_ETHERNET_IP101
36#include "esp_eth_phy_ip101.h"
37#endif
38#ifdef USE_ETHERNET_KSZ8081
39#include "esp_eth_phy_ksz80xx.h"
40#endif
41#ifdef USE_ETHERNET_W5500
42#include "esp_eth_mac_w5500.h"
43#include "esp_eth_phy_w5500.h"
44#endif
45#ifdef USE_ETHERNET_DM9051
46#include "esp_eth_mac_dm9051.h"
47#include "esp_eth_phy_dm9051.h"
48#endif
49#ifdef USE_ETHERNET_KSZ8851SNL
50#include "esp_eth_mac_ksz8851snl.h"
51#include "esp_eth_phy_ksz8851snl.h"
52#endif
53#endif // ESP_IDF_VERSION >= 6.0.0
54
55// LAN867x header exists on all IDF versions (external component since IDF 5.3)
56#ifdef USE_ETHERNET_LAN8670
57#include "esp_eth_phy_lan867x.h"
58#endif
59
60// ENC28J60 header exists on all IDF versions (always an external component)
61#ifdef USE_ETHERNET_ENC28J60
62#include "esp_eth_enc28j60.h"
63#endif
64
65// CH390 headers exist on all IDF versions (always an external component)
66#ifdef USE_ETHERNET_CH390
67#include "esp_eth_mac_ch390.h"
68#include "esp_eth_phy_ch390.h"
69#endif
70
71#ifdef USE_ETHERNET_SPI
72#include <driver/gpio.h>
73#include <driver/spi_master.h>
74#ifdef USE_SPI
76#endif
77#endif
78
79namespace esphome::ethernet {
80
81ESPHOME_LOG_TAG(TAG, "ethernet");
82
83// PHY register size for hex logging
84static constexpr size_t PHY_REG_SIZE = 2;
85
86// Dual wifi + ethernet SPI builds: the one place internal RAM is short and lwip's other buffers are
87// already in PSRAM. Not with L2 TAP, whose filter lives in the glue's input path this replaces.
88#if defined(USE_PSRAM) && defined(USE_ETHERNET_SPI) && defined(USE_WIFI) && !defined(CONFIG_ESP_NETIF_L2_TAP)
89#define USE_ETHERNET_RX_PSRAM
90// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) - reported by dump_config()
91static bool rx_psram_installed = false;
92
93// ESP-IDF ethernet drivers malloc() every received frame in internal RAM, where it stays until lwIP
94// hands it to the application. Move it to PSRAM; if that fails the frame is passed on where it is.
95static esp_err_t eth_input_to_psram(esp_eth_handle_t handle, uint8_t *buffer, uint32_t length, void *priv) {
96 auto *copy = static_cast<uint8_t *>(heap_caps_malloc(length, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
97 if (copy != nullptr) {
98 memcpy(copy, buffer, length);
99 free(buffer); // NOLINT(cppcoreguidelines-no-malloc) - allocated by the driver with malloc()
100 buffer = copy;
101 } else {
102 static bool warned = false; // once, this runs per frame in the driver's task
103 if (!warned) {
104 warned = true;
105 ESP_LOGW(TAG, "PSRAM allocation failed, frame kept in internal RAM (reported once)");
106 }
107 }
108 return esp_netif_receive(static_cast<esp_netif_t *>(priv), buffer, length, nullptr);
109}
110#endif
111
113 ESP_LOGE(TAG, "%s: (%d) %s", message, err, esp_err_to_name(err));
114 this->mark_failed();
115}
116
117#define ESPHL_ERROR_CHECK(err, message) \
118 if ((err) != ESP_OK) { \
119 this->log_error_and_mark_failed_(err, message); \
120 return; \
121 }
122
123#define ESPHL_ERROR_CHECK_RET(err, message, ret) \
124 if ((err) != ESP_OK) { \
125 this->log_error_and_mark_failed_(err, message); \
126 return ret; \
127 }
128
131
132#ifdef USE_ETHERNET_IP_STATE_LISTENERS
133 // The IP events arrive on the event task; the listeners publish states, so notify them here
134 if (this->ip_state_pending_.load(std::memory_order_acquire) != 0) {
135 this->ip_state_pending_.store(0, std::memory_order_relaxed);
137 }
138#endif
139
140 switch (this->state_) {
142 if (this->started_) {
143 ESP_LOGI(TAG, "Starting connection");
145 this->start_connect_();
146 }
147 break;
149 if (!this->started_) {
150 ESP_LOGI(TAG, "Stopped connection");
152 } else if (this->connected_) {
153 // connection established
154 ESP_LOGI(TAG, "Connected");
156
157 this->dump_connect_params_();
158 this->status_clear_warning();
159#ifdef USE_ETHERNET_CONNECT_TRIGGER
161#endif
162 } else if (now - this->connect_begin_ > 15000) {
163 ESP_LOGW(TAG, "Connecting failed; reconnecting");
164 this->start_connect_();
165 }
166 break;
168 if (!this->started_) {
169 ESP_LOGI(TAG, "Stopped connection");
171#ifdef USE_ETHERNET_DISCONNECT_TRIGGER
173#endif
174 } else if (!this->connected_) {
175 ESP_LOGW(TAG, "Connection lost; reconnecting");
177 this->start_connect_();
178#ifdef USE_ETHERNET_DISCONNECT_TRIGGER
180#endif
181 } else {
182 this->finish_connect_();
183 // When connected and stable, disable the loop to save CPU cycles
184 this->disable_loop();
185 }
186 break;
187 }
188}
189
191 if (esp_reset_reason() != ESP_RST_DEEPSLEEP) {
192 // Delay here to allow power to stabilise before Ethernet is initialized.
193 delay(300); // NOLINT
194 }
195
196 if (this->enable_on_boot_) {
197 this->ethernet_lazy_init_();
198 if (!this->ethernet_initialized_) {
199 // lazy_init bailed early via ESPHL_ERROR_CHECK or mark_failed; nothing more to do.
200 return;
201 }
202 esp_err_t err = esp_eth_start(this->eth_handle_);
203 ESPHL_ERROR_CHECK(err, "ETH start error");
204 } else {
205 ESP_LOGCONFIG(TAG, "Skipping init (enable_on_boot: false)");
206 this->disabled_ = true;
207 }
208}
209
211 if (this->ethernet_initialized_)
212 return;
213
214 esp_err_t err;
215
216#ifdef USE_ETHERNET_SPI
217 // Install GPIO ISR handler to be able to service SPI Eth modules interrupts
218 gpio_install_isr_service(0);
219
220 spi_host_device_t host;
221#ifdef USE_SPI
222 if (this->spi_parent_ != nullptr) {
223 // The bus is owned and already initialized by the spi component; share its host.
224 host = this->spi_parent_->get_interface();
225 } else
226#endif
227 {
228 spi_bus_config_t buscfg = {
229 .mosi_io_num = this->mosi_pin_,
230 .miso_io_num = this->miso_pin_,
231 .sclk_io_num = this->clk_pin_,
232 .quadwp_io_num = -1,
233 .quadhd_io_num = -1,
234 .data4_io_num = -1,
235 .data5_io_num = -1,
236 .data6_io_num = -1,
237 .data7_io_num = -1,
238 .max_transfer_sz = 0,
239 .flags = 0,
240 .intr_flags = 0,
241 };
242
243 host = this->interface_;
244
245 err = spi_bus_initialize(host, &buscfg, SPI_DMA_CH_AUTO);
246 ESPHL_ERROR_CHECK(err, "SPI bus initialize error");
247 }
248#endif
249 // Network interface setup handled by network component
250
251 esp_netif_config_t cfg = ESP_NETIF_DEFAULT_ETH();
252 this->eth_netif_ = esp_netif_new(&cfg);
253
254 // Init MAC and PHY configs to default
255 eth_phy_config_t phy_config = ETH_PHY_DEFAULT_CONFIG();
256 eth_mac_config_t mac_config = ETH_MAC_DEFAULT_CONFIG();
257
258#ifdef USE_ETHERNET_SPI // Configure SPI interface and Ethernet driver for specific SPI module
259 spi_device_interface_config_t devcfg = {
260 .command_bits = 0,
261 .address_bits = 0,
262 .dummy_bits = 0,
263 .mode = 0,
264 .duty_cycle_pos = 0,
265 .cs_ena_pretrans = 0,
266 .cs_ena_posttrans = 0,
267 .clock_speed_hz = this->clock_speed_,
268 .input_delay_ns = 0,
269 .spics_io_num = this->cs_pin_,
270 .flags = 0,
271 .queue_size = 20,
272 .pre_cb = nullptr,
273 .post_cb = nullptr,
274 };
275
276#if defined(USE_ETHERNET_W5500)
277 eth_w5500_config_t w5500_config = ETH_W5500_DEFAULT_CONFIG(host, &devcfg);
278#elif defined(USE_ETHERNET_DM9051)
279 eth_dm9051_config_t dm9051_config = ETH_DM9051_DEFAULT_CONFIG(host, &devcfg);
280#elif defined(USE_ETHERNET_ENC28J60)
281 eth_enc28j60_config_t enc28j60_config = ETH_ENC28J60_DEFAULT_CONFIG(host, &devcfg);
282#elif defined(USE_ETHERNET_CH390)
283 eth_ch390_config_t ch390_config = ETH_CH390_DEFAULT_CONFIG(host, &devcfg);
284#elif defined(USE_ETHERNET_KSZ8851SNL)
285 eth_ksz8851snl_config_t ksz8851snl_config = ETH_KSZ8851SNL_DEFAULT_CONFIG(host, &devcfg);
286#endif
287
288#if defined(USE_ETHERNET_W5500)
289#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
290 w5500_config.base.int_gpio_num = this->interrupt_pin_;
291#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
292 w5500_config.base.poll_period_ms = this->polling_interval_;
293#endif
294#else
295 w5500_config.int_gpio_num = this->interrupt_pin_;
296#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
297 w5500_config.poll_period_ms = this->polling_interval_;
298#endif
299#endif
300 // Install the custom SPI driver that offloads the bulk RX/TX frame transfers off the busy-wait
301 // path. w5500_config (and the devcfg it references) outlives esp_eth_mac_new_w5500() below, which
302 // runs the driver's init().
303 install_w5500_async_spi(w5500_config);
304#elif defined(USE_ETHERNET_DM9051)
305 dm9051_config.int_gpio_num = this->interrupt_pin_;
306#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
307 dm9051_config.poll_period_ms = this->polling_interval_;
308#endif
309#elif defined(USE_ETHERNET_ENC28J60)
310 // ENC28J60 does not support poll_period_ms. CS must stay asserted for the chip's CS hold
311 // time (t10, 210 ns) after the last clock or MAC/MII register reads fail ("wrong chip ID")
312 enc28j60_config.spi_devcfg->cs_ena_posttrans = enc28j60_cal_spi_cs_hold_time((this->clock_speed_ + 999999) / 1000000);
313 enc28j60_config.int_gpio_num = this->interrupt_pin_;
314#elif defined(USE_ETHERNET_CH390)
315 ch390_config.int_gpio_num = this->interrupt_pin_;
316#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
317 ch390_config.poll_period_ms = this->polling_interval_;
318#endif
319#elif defined(USE_ETHERNET_KSZ8851SNL)
320 ksz8851snl_config.int_gpio_num = this->interrupt_pin_;
321#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
322 ksz8851snl_config.poll_period_ms = this->polling_interval_;
323#endif
324#endif
325
326 phy_config.phy_addr = this->phy_addr_spi_;
327 phy_config.reset_gpio_num = this->reset_pin_;
328
329 esp_eth_mac_t *mac = nullptr;
330#elif defined(USE_ETHERNET_OPENETH)
331 esp_eth_mac_t *mac = esp_eth_mac_new_openeth(&mac_config);
332#else
333 phy_config.phy_addr = this->phy_addr_;
334 phy_config.reset_gpio_num = this->power_pin_;
335
336 eth_esp32_emac_config_t esp32_emac_config = eth_esp32_emac_default_config();
337#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 0)
338 esp32_emac_config.smi_gpio.mdc_num = this->mdc_pin_;
339 esp32_emac_config.smi_gpio.mdio_num = this->mdio_pin_;
340#else
341 esp32_emac_config.smi_mdc_gpio_num = this->mdc_pin_;
342 esp32_emac_config.smi_mdio_gpio_num = this->mdio_pin_;
343#endif
344 // The RGMII types (GENERIC, YT8531) use the RGMII interface and default GPIO map from
345 // eth_esp32_emac_default_config(); writing the RMII clock config would clobber that
346 // union, so skip the RMII clock override for them.
347 if (this->type_ != ETHERNET_TYPE_GENERIC && this->type_ != ETHERNET_TYPE_YT8531) {
348 esp32_emac_config.clock_config.rmii.clock_mode = this->clk_mode_;
349 esp32_emac_config.clock_config.rmii.clock_gpio =
350 static_cast<decltype(esp32_emac_config.clock_config.rmii.clock_gpio)>(this->clk_pin_);
351 }
352
353 esp_eth_mac_t *mac = esp_eth_mac_new_esp32(&esp32_emac_config, &mac_config);
354#endif
355
356 switch (this->type_) {
357#ifdef USE_ETHERNET_OPENETH
359 phy_config.autonego_timeout_ms = 1000;
360#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
361 this->phy_ = esp_eth_phy_new_generic(&phy_config);
362#else
363 this->phy_ = esp_eth_phy_new_dp83848(&phy_config);
364#endif
365 break;
366 }
367#endif
368#if CONFIG_ETH_USE_ESP32_EMAC
369#ifdef USE_ETHERNET_LAN8720
371 this->phy_ = esp_eth_phy_new_lan87xx(&phy_config);
372 break;
373 }
374#endif
375#ifdef USE_ETHERNET_RTL8201
377 this->phy_ = esp_eth_phy_new_rtl8201(&phy_config);
378 break;
379 }
380#endif
381#ifdef USE_ETHERNET_DP83848
383 this->phy_ = esp_eth_phy_new_dp83848(&phy_config);
384 break;
385 }
386#endif
387#ifdef USE_ETHERNET_IP101
388 case ETHERNET_TYPE_IP101: {
389 this->phy_ = esp_eth_phy_new_ip101(&phy_config);
390 break;
391 }
392#endif
393#ifdef USE_ETHERNET_JL1101
395 // PlatformIO (pioarduino): builtin esp_eth_phy_new_jl1101() on all IDF versions
396 // Non-PlatformIO: custom ESPHome driver (esp_eth_phy_jl1101.c)
397 this->phy_ = esp_eth_phy_new_jl1101(&phy_config);
398 break;
399 }
400#endif
401#ifdef USE_ETHERNET_KSZ8081
404 this->phy_ = esp_eth_phy_new_ksz80xx(&phy_config);
405 break;
406 }
407#endif
408#ifdef USE_ETHERNET_LAN8670
410 this->phy_ = esp_eth_phy_new_lan867x(&phy_config);
411 break;
412 }
413#endif
414#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
415 // GENERIC and YT8531 both use the built-in generic 802.3 PHY driver; YT8531 gets
416 // extra chip-specific tuning applied later in ethernet_lazy_init_().
417#ifdef USE_ETHERNET_GENERIC
419#endif
420#ifdef USE_ETHERNET_YT8531
422#endif
423#if defined(USE_ETHERNET_GENERIC) || defined(USE_ETHERNET_YT8531)
424 this->phy_ = esp_eth_phy_new_generic(&phy_config);
425 break;
426#endif
427#endif
428#endif
429#ifdef USE_ETHERNET_SPI
430#if defined(USE_ETHERNET_W5500)
431 case ETHERNET_TYPE_W5500: {
432 mac = esp_eth_mac_new_w5500(&w5500_config, &mac_config);
433 this->phy_ = esp_eth_phy_new_w5500(&phy_config);
434 break;
435 }
436#elif defined(USE_ETHERNET_DM9051)
438 mac = esp_eth_mac_new_dm9051(&dm9051_config, &mac_config);
439 this->phy_ = esp_eth_phy_new_dm9051(&phy_config);
440 break;
441 }
442#elif defined(USE_ETHERNET_ENC28J60)
444 mac = esp_eth_mac_new_enc28j60(&enc28j60_config, &mac_config);
445 this->phy_ = esp_eth_phy_new_enc28j60(&phy_config);
446 break;
447 }
448#elif defined(USE_ETHERNET_CH390)
449 case ETHERNET_TYPE_CH390: {
450 mac = esp_eth_mac_new_ch390(&ch390_config, &mac_config);
451 this->phy_ = esp_eth_phy_new_ch390(&phy_config);
452 break;
453 }
454#elif defined(USE_ETHERNET_KSZ8851SNL)
456 mac = esp_eth_mac_new_ksz8851snl(&ksz8851snl_config, &mac_config);
457 this->phy_ = esp_eth_phy_new_ksz8851snl(&phy_config);
458 break;
459 }
460#endif
461#endif
462 default: {
463 this->mark_failed();
464 return;
465 }
466 }
467
468 esp_eth_config_t eth_config = ETH_DEFAULT_CONFIG(mac, this->phy_);
469 this->eth_handle_ = nullptr;
470 err = esp_eth_driver_install(&eth_config, &this->eth_handle_);
471 ESPHL_ERROR_CHECK(err, "ETH driver install error");
472
473#ifndef USE_ETHERNET_SPI
474#ifdef USE_ETHERNET_KSZ8081
475 if (this->type_ == ETHERNET_TYPE_KSZ8081RNA && this->clk_mode_ == EMAC_CLK_OUT) {
476 // KSZ8081RNA default is incorrect. It expects a 25MHz clock instead of the 50MHz we provide.
478 }
479#endif // USE_ETHERNET_KSZ8081
480
481#ifdef ESPHOME_ETHERNET_PHY_REGISTER_COUNT
482 for (const auto &phy_register : this->phy_registers_) {
483 this->write_phy_register_(mac, phy_register);
484 }
485#endif
486
487#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
488#ifdef USE_ETHERNET_GENERIC
489 // The generic 802.3 PHY driver only resets the PHY in its init; it never enables
490 // auto-negotiation. A PHY that resets into a forced-speed mode (BMCR auto-nego bit
491 // clear) therefore stays there, and esp_eth_start() skips negotiation because the
492 // driver cached auto_nego_en=false at install time. Force auto-negotiation on here
493 // (which also updates that cached state) so esp_eth_start() restarts a proper
494 // negotiation. (YT8531 does this as part of its own chip-specific init below.)
495 if (this->type_ == ETHERNET_TYPE_GENERIC) {
496 bool autoneg_enable = true;
497 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_S_AUTONEGO, &autoneg_enable);
498 ESPHL_ERROR_CHECK(err, "Enable auto-negotiation failed");
499 }
500#endif
501#ifdef USE_ETHERNET_YT8531
502 if (this->type_ == ETHERNET_TYPE_YT8531) {
503 this->yt8531_phy_init_();
504 if (this->is_failed())
505 return;
506 }
507#endif
508#endif // ESP_IDF_VERSION >= 6.0.0
509#endif // !USE_ETHERNET_SPI
510
511 // use ESP internal eth mac
512 uint8_t mac_addr[MAC_ADDRESS_SIZE];
513 if (this->fixed_mac_.has_value()) {
514 memcpy(mac_addr, this->fixed_mac_->data(), MAC_ADDRESS_SIZE);
515 } else {
516 esp_read_mac(mac_addr, ESP_MAC_ETH);
517 }
518 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_S_MAC_ADDR, mac_addr);
519 ESPHL_ERROR_CHECK(err, "set mac address error");
520
521 /* attach Ethernet driver to TCP/IP stack */
522 err = esp_netif_attach(this->eth_netif_, esp_eth_new_netif_glue(this->eth_handle_));
523 ESPHL_ERROR_CHECK(err, "ETH netif attach error");
524#ifdef USE_ETHERNET_RX_PSRAM
525 // The glue frees every receive buffer with free(), so the replacement buffer must come from the heap
526 if (esp_psram_is_initialized()) {
527 err = esp_eth_update_input_path(this->eth_handle_, eth_input_to_psram, this->eth_netif_);
528 rx_psram_installed = err == ESP_OK;
529 if (!rx_psram_installed) {
530 ESP_LOGW(TAG, "PSRAM RX path not installed: %s", esp_err_to_name(err));
531 }
532 }
533#endif
534#if USE_NETWORK_IPV6 && ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)
535 // Since IDF 5.5 the internal EMAC drops multicast groups that were never added (before,
536 // it passed all multicast), and lwIP never adds all-nodes, so router advertisements
537 // were lost and SLAAC never ran.
538 {
539 uint8_t all_nodes[6] = {0x33, 0x33, 0x00, 0x00, 0x00, 0x01};
540 if (esp_err_t filter_err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_ADD_MAC_FILTER, all_nodes);
541 filter_err != ESP_OK) {
542 ESP_LOGD(TAG, "IPv6 all-nodes multicast filter not added: %s", esp_err_to_name(filter_err));
543 }
544 }
545#endif
546
547 // Register user defined event handers
548 err = esp_event_handler_register(ETH_EVENT, ESP_EVENT_ANY_ID, &EthernetComponent::eth_event_handler, nullptr);
549 ESPHL_ERROR_CHECK(err, "ETH event handler register error");
550 err = esp_event_handler_register(IP_EVENT, IP_EVENT_ETH_GOT_IP, &EthernetComponent::got_ip_event_handler, nullptr);
551 ESPHL_ERROR_CHECK(err, "GOT IP event handler register error");
552#if USE_NETWORK_IPV6
553 err = esp_event_handler_register(IP_EVENT, IP_EVENT_GOT_IP6, &EthernetComponent::got_ip6_event_handler, nullptr);
554 ESPHL_ERROR_CHECK(err, "GOT IPv6 event handler register error");
555#endif /* USE_NETWORK_IPV6 */
556
557 this->ethernet_initialized_ = true;
558}
559
561 if (!this->disabled_)
562 return;
563
564 ESP_LOGD(TAG, "Enabling");
565 this->ethernet_lazy_init_();
566 if (!this->ethernet_initialized_) {
567 ESP_LOGE(TAG, "Cannot enable - init failed");
568 return;
569 }
570 esp_err_t err = esp_eth_start(this->eth_handle_);
571 if (err != ESP_OK) {
572 ESP_LOGE(TAG, "esp_eth_start failed: %s", esp_err_to_name(err));
573 return;
574 }
575 this->disabled_ = false;
576 // The ETH_EVENT_START handler will set started_=true; the loop state machine
577 // will then drive the STOPPED -> CONNECTING -> CONNECTED transitions.
578 this->enable_loop();
579}
580
582 if (this->disabled_)
583 return;
584
585 ESP_LOGD(TAG, "Disabling");
586 esp_err_t err = esp_eth_stop(this->eth_handle_);
587 if (err != ESP_OK) {
588 ESP_LOGW(TAG, "esp_eth_stop failed: %s — disabling anyway", esp_err_to_name(err));
589 }
590 this->disabled_ = true;
591 // ETH_EVENT_STOP will clear started_; loop() will transition to STOPPED.
592}
593
595 const char *eth_type;
596 switch (this->type_) {
597#ifdef USE_ETHERNET_LAN8720
599 eth_type = "LAN8720";
600 break;
601#endif
602#ifdef USE_ETHERNET_RTL8201
604 eth_type = "RTL8201";
605 break;
606#endif
607#ifdef USE_ETHERNET_DP83848
609 eth_type = "DP83848";
610 break;
611#endif
612#ifdef USE_ETHERNET_IP101
614 eth_type = "IP101";
615 break;
616#endif
617#ifdef USE_ETHERNET_JL1101
619 eth_type = "JL1101";
620 break;
621#endif
622#ifdef USE_ETHERNET_KSZ8081
624 eth_type = "KSZ8081";
625 break;
626
628 eth_type = "KSZ8081RNA";
629 break;
630#endif
631#if defined(USE_ETHERNET_W5500)
633 eth_type = "W5500";
634 break;
635#elif defined(USE_ETHERNET_DM9051)
637 eth_type = "DM9051";
638 break;
639#elif defined(USE_ETHERNET_ENC28J60)
641 eth_type = "ENC28J60";
642 break;
643#elif defined(USE_ETHERNET_CH390)
645 eth_type = "CH390";
646 break;
647#elif defined(USE_ETHERNET_KSZ8851SNL)
649 eth_type = "KSZ8851SNL";
650 break;
651#endif
652#ifdef USE_ETHERNET_OPENETH
654 eth_type = "OPENETH";
655 break;
656#endif
657#ifdef USE_ETHERNET_LAN8670
659 eth_type = "LAN8670";
660 break;
661#endif
662#ifdef USE_ETHERNET_GENERIC
664 eth_type = "Generic (RGMII)";
665 break;
666#endif
667#ifdef USE_ETHERNET_YT8531
669 eth_type = "YT8531 (RGMII)";
670 break;
671#endif
672
673 default:
674 eth_type = "Unknown";
675 break;
676 }
677
678 ESP_LOGCONFIG(TAG,
679 "Ethernet:\n"
680 " Connected: %s",
681 YESNO(this->is_connected()));
682 this->dump_connect_params_();
683#ifdef USE_ETHERNET_SPI
684#ifdef USE_SPI
685 if (this->spi_parent_ != nullptr) {
686 // Pins and interface come from the shared spi bus; only CS is ours.
687 ESP_LOGCONFIG(TAG, " CS Pin: %u", this->cs_pin_);
688 } else
689#endif
690 {
691 ESP_LOGCONFIG(TAG,
692 " CLK Pin: %u\n"
693 " MISO Pin: %u\n"
694 " MOSI Pin: %u\n"
695 " CS Pin: %u",
696 this->clk_pin_, this->miso_pin_, this->mosi_pin_, this->cs_pin_);
697 const char *spi_interface = "spi3";
698 if (this->interface_ == SPI2_HOST) {
699 spi_interface = "spi2";
700 }
701 ESP_LOGCONFIG(TAG, " Interface: %s", spi_interface);
702 }
703#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
704 if (this->polling_interval_ != 0) {
705 ESP_LOGCONFIG(TAG, " Polling Interval: %" PRIu32 " ms", this->polling_interval_);
706 } else
707#endif
708 {
709 ESP_LOGCONFIG(TAG, " IRQ Pin: %d", this->interrupt_pin_);
710 }
711 ESP_LOGCONFIG(TAG,
712 " Reset Pin: %d\n"
713 " Clock Speed: %d MHz",
714 this->reset_pin_, this->clock_speed_ / 1000000);
715#else
716 if (this->power_pin_ != -1) {
717 ESP_LOGCONFIG(TAG, " Power Pin: %u", this->power_pin_);
718 }
719 ESP_LOGCONFIG(TAG,
720 " CLK Pin: %u\n"
721 " MDC Pin: %u\n"
722 " MDIO Pin: %u\n"
723 " PHY addr: %u",
724 this->clk_pin_, this->mdc_pin_, this->mdio_pin_, this->phy_addr_);
725#endif
726 ESP_LOGCONFIG(TAG, " Type: %s", eth_type);
727#ifdef USE_ETHERNET_RX_PSRAM
728 // Only known once the driver is up; with enable_on_boot: false that is after this dump
729 if (this->ethernet_initialized_) {
730 ESP_LOGCONFIG(TAG, " RX frames: %s",
731 rx_psram_installed ? LOG_STR_LITERAL("PSRAM") : LOG_STR_LITERAL("internal RAM"));
732 }
733#endif
734}
735
737 network::IPAddresses addresses;
738 if (!this->ethernet_initialized_)
739 return addresses; // all-zero IPs
740 esp_netif_ip_info_t ip;
741 esp_err_t err = esp_netif_get_ip_info(this->eth_netif_, &ip);
742 if (err != ESP_OK) {
743 ESP_LOGV(TAG, "esp_netif_get_ip_info failed: %s", esp_err_to_name(err));
744 // TODO: do something smarter
745 // return false;
746 } else {
747 addresses[0] = network::IPAddress(&ip.ip);
748 }
749#if USE_NETWORK_IPV6
750 network::fill_ip6_addresses(this->eth_netif_, addresses);
751#endif /* USE_NETWORK_IPV6 */
752
753 return addresses;
754}
755
758 const ip_addr_t *dns_ip = dns_getserver(num);
759 return dns_ip;
760}
761
762void EthernetComponent::eth_event_handler(void *arg, esp_event_base_t event_base, int32_t event, void *event_data) {
763 const char *event_name;
764
765 switch (event) {
766 case ETHERNET_EVENT_START:
767 event_name = "ETH started";
770 break;
771 case ETHERNET_EVENT_STOP:
772 event_name = "ETH stopped";
775 global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
776 break;
777 case ETHERNET_EVENT_CONNECTED:
778 event_name = "ETH connected";
779 // For static IP configurations, GOT_IP event may not fire, so notify IP listeners here
780#if defined(USE_ETHERNET_IP_STATE_LISTENERS) && defined(USE_ETHERNET_MANUAL_IP)
781 global_eth_component->ip_state_pending_.store(1, std::memory_order_release);
783#endif
784#if USE_NETWORK_IPV6
785 // Start SLAAC on link-up, not after the DHCPv4 lease. This also restores the
786 // link-local after a link flap, which clears the IPv6 addresses.
787 if (esp_err_t ll_err = esp_netif_create_ip6_linklocal(global_eth_component->eth_netif_); ll_err != ESP_OK) {
788 ESP_LOGW(TAG, "esp_netif_create_ip6_linklocal failed on link-up: %s", esp_err_to_name(ll_err));
789 }
790#endif /* USE_NETWORK_IPV6 */
791 break;
792 case ETHERNET_EVENT_DISCONNECTED:
793 event_name = "ETH disconnected";
795 global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
796 break;
797 default:
798 return;
799 }
800
801 ESP_LOGV(TAG, "[Ethernet event] %s (num=%" PRId32 ")", event_name, event);
802}
803
804void EthernetComponent::got_ip_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id,
805 void *event_data) {
806 ip_event_got_ip_t *event = (ip_event_got_ip_t *) event_data;
807 const esp_netif_ip_info_t *ip_info = &event->ip_info;
808 ESP_LOGV(TAG, "[Ethernet event] ETH Got IP " IPSTR, IP2STR(&ip_info->ip));
810#ifdef USE_ETHERNET_IP_STATE_LISTENERS
811 global_eth_component->ip_state_pending_.store(1, std::memory_order_release);
812#endif
813#if USE_NETWORK_IPV6 && (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
814 global_eth_component->connected_ = global_eth_component->ipv6_count_ >= USE_NETWORK_MIN_IPV6_ADDR_COUNT;
815 global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
816#else
818 global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
819#endif /* USE_NETWORK_IPV6 */
820}
821
822#if USE_NETWORK_IPV6
823void EthernetComponent::got_ip6_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id,
824 void *event_data) {
825 ip_event_got_ip6_t *event = (ip_event_got_ip6_t *) event_data;
826 ESP_LOGV(TAG, "[Ethernet event] ETH Got IPv6: " IPV6STR, IPV62STR(event->ip6_info.ip));
827 // Count the addresses on the interface, not the events: recreating the link-local
828 // after a link flap fires another event for the same address.
829 struct esp_ip6_addr if_ip6s[CONFIG_LWIP_IPV6_NUM_ADDRESSES];
830 global_eth_component->ipv6_count_ = esp_netif_get_all_ip6(global_eth_component->eth_netif_, if_ip6s);
831#ifdef USE_ETHERNET_IP_STATE_LISTENERS
832 global_eth_component->ip_state_pending_.store(1, std::memory_order_release);
833#endif
834#if (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
836 global_eth_component->got_ipv4_address_ && (global_eth_component->ipv6_count_ >= USE_NETWORK_MIN_IPV6_ADDR_COUNT);
837 global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
838#else
840 global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
841#endif
842}
843#endif /* USE_NETWORK_IPV6 */
844
845#if USE_NETWORK_IPV6
846// Create the link-local address unless the interface already has one, including one still in
847// duplicate address detection: recreating it would restart DAD. esp_netif_get_ip6_linklocal()
848// only reports a preferred address, so ask lwIP for the slot state instead.
850 if (auto *netif = static_cast<struct netif *>(esp_netif_get_netif_impl(this->eth_netif_)); netif != nullptr) {
851 u8_t state;
852 {
854 state = netif_ip6_addr_state(netif, 0);
855 }
856 if (ip6_addr_istentative(state) || ip6_addr_isvalid(state)) {
857 return ESP_OK;
858 }
859 }
860 esp_err_t err = esp_netif_create_ip6_linklocal(this->eth_netif_);
861 if (err == ESP_OK) {
862 ESP_LOGD(TAG, "IPv6 link-local address created");
863 }
864 return err;
865}
866#endif /* USE_NETWORK_IPV6 */
867
869#if USE_NETWORK_IPV6
870 // Retry IPv6 link-local setup if it failed during initial connect
871 // This handles the case where min_ipv6_addr_count is NOT set (or is 0),
872 // allowing us to reach CONNECTED state with just IPv4.
873 // If IPv6 setup failed in start_connect_() because the interface wasn't ready:
874 // - Bootup timing issues (#10281)
875 // - Cable unplugged/network interruption (#10705)
876 // We can now retry since we're in CONNECTED state and the interface is definitely up.
877 if (!this->ipv6_setup_done_) {
878 this->ensure_ip6_linklocal_();
879 // Always set the flag to prevent continuous retries
880 // If IPv6 setup fails here with the interface up and stable, it's
881 // likely a persistent issue (IPv6 disabled at router, hardware
882 // limitation, etc.) that won't be resolved by further retries.
883 // The device continues to work with IPv4.
884 this->ipv6_setup_done_ = true;
885 }
886#endif /* USE_NETWORK_IPV6 */
887}
888
891#if USE_NETWORK_IPV6
892 // Recount rather than zero: addresses that survive a reconnect are not announced again.
893 struct esp_ip6_addr if_ip6s[CONFIG_LWIP_IPV6_NUM_ADDRESSES];
894 global_eth_component->ipv6_count_ = esp_netif_get_all_ip6(this->eth_netif_, if_ip6s);
895 this->ipv6_setup_done_ = false;
896#endif /* USE_NETWORK_IPV6 */
897 this->connect_begin_ = millis();
898 this->status_set_warning(LOG_STR("waiting for IP configuration"));
899
900 esp_err_t err;
901 err = esp_netif_set_hostname(this->eth_netif_, App.get_name().c_str());
902 if (err != ERR_OK) {
903 ESP_LOGW(TAG, "esp_netif_set_hostname failed: %s", esp_err_to_name(err));
904 }
905
906 esp_netif_ip_info_t info{};
907#ifdef USE_ETHERNET_MANUAL_IP
908 const ManualIP manual_ip = load_manual_ip();
909 info.ip = manual_ip.static_ip;
910 info.gw = manual_ip.gateway;
911 info.netmask = manual_ip.subnet;
912#endif
913
914 esp_netif_dhcp_status_t status = ESP_NETIF_DHCP_INIT;
915
916 err = esp_netif_dhcpc_get_status(this->eth_netif_, &status);
917 ESPHL_ERROR_CHECK(err, "DHCPC Get Status Failed!");
918
919 ESP_LOGV(TAG, "DHCP Client Status: %d", status);
920
921 err = esp_netif_dhcpc_stop(this->eth_netif_);
922 if (err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED) {
923 ESPHL_ERROR_CHECK(err, "DHCPC stop error");
924 }
925
926 err = esp_netif_set_ip_info(this->eth_netif_, &info);
927 ESPHL_ERROR_CHECK(err, "DHCPC set IP info error");
928
929#ifdef USE_ETHERNET_MANUAL_IP
930 // Set DNS through esp_netif so the servers are stored in the netif's own
931 // dns[] array; raw dns_setserver() would be lost when the default-route
932 // arbitration re-applies the default netif's DNS.
933 // Log-only on failure: the link still has a working IP/gateway, so degraded
934 // name resolution does not justify marking the whole component failed.
935 esp_netif_dns_info_t dns{};
936 if (manual_ip.dns1.is_set()) {
937 dns.ip = manual_ip.dns1;
938 err = esp_netif_set_dns_info(this->eth_netif_, ESP_NETIF_DNS_MAIN, &dns);
939 if (err != ESP_OK) {
940 ESP_LOGE(TAG, "Set main DNS failed: %s", esp_err_to_name(err));
941 }
942 }
943 if (manual_ip.dns2.is_set()) {
944 dns.ip = manual_ip.dns2;
945 err = esp_netif_set_dns_info(this->eth_netif_, ESP_NETIF_DNS_BACKUP, &dns);
946 if (err != ESP_OK) {
947 ESP_LOGE(TAG, "Set backup DNS failed: %s", esp_err_to_name(err));
948 }
949 }
950#else
951 err = esp_netif_dhcpc_start(this->eth_netif_);
952 if (err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED) {
953 ESPHL_ERROR_CHECK(err, "DHCPC start error");
954 }
955#endif
956#if USE_NETWORK_IPV6
957 // Attempt to create IPv6 link-local address
958 // We MUST attempt this here, not just in finish_connect_(), because with
959 // min_ipv6_addr_count set, the component won't reach CONNECTED state without IPv6.
960 // However, this may fail with ESP_FAIL if the interface is not up yet:
961 // - At bootup when link isn't ready (#10281)
962 // - After disconnection/cable unplugged (#10705)
963 // We'll retry in finish_connect_() if it fails here.
964 err = this->ensure_ip6_linklocal_();
965 if (err != ESP_OK) {
966 if (err == ESP_ERR_ESP_NETIF_INVALID_PARAMS) {
967 // This is a programming error, not a transient failure
968 ESPHL_ERROR_CHECK(err, "esp_netif_create_ip6_linklocal invalid parameters");
969 } else {
970 // ESP_FAIL means the interface isn't up yet
971 // This is expected and non-fatal, happens in multiple scenarios:
972 // - During reconnection after network interruptions (#10705)
973 // - At bootup when the link isn't ready yet (#10281)
974 // We'll retry once we reach CONNECTED state and the interface is up
975 ESP_LOGW(TAG, "esp_netif_create_ip6_linklocal failed: %s", esp_err_to_name(err));
976 // Don't mark component as failed - this is a transient error
977 }
978 }
979#endif /* USE_NETWORK_IPV6 */
980
981 this->connect_begin_ = millis();
982 this->status_set_warning();
983}
984
986 if (!this->ethernet_initialized_) {
987 ESP_LOGCONFIG(TAG, " uninitialized/disabled");
988 return;
989 }
990 esp_netif_ip_info_t ip;
991 esp_netif_get_ip_info(this->eth_netif_, &ip);
992 const ip_addr_t *dns_ip1;
993 const ip_addr_t *dns_ip2;
994 {
996 dns_ip1 = dns_getserver(0);
997 dns_ip2 = dns_getserver(1);
998 }
999
1000 // Use stack buffers for IP address formatting to avoid heap allocations
1001 char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
1002 char subnet_buf[network::IP_ADDRESS_BUFFER_SIZE];
1003 char gateway_buf[network::IP_ADDRESS_BUFFER_SIZE];
1004 char dns1_buf[network::IP_ADDRESS_BUFFER_SIZE];
1005 char dns2_buf[network::IP_ADDRESS_BUFFER_SIZE];
1006 char mac_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
1007 uint16_t link_speed = 10;
1008 switch (this->get_link_speed()) {
1009 case ETH_SPEED_100M:
1010 link_speed = 100;
1011 break;
1012#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 1, 0)
1013 case ETH_SPEED_1000M:
1014 link_speed = 1000;
1015 break;
1016#endif
1017 default:
1018 break;
1019 }
1020 ESP_LOGCONFIG(TAG,
1021 " IP Address: %s\n"
1022 " Hostname: '%s'\n"
1023 " Subnet: %s\n"
1024 " Gateway: %s\n"
1025 " DNS1: %s\n"
1026 " DNS2: %s\n"
1027 " MAC Address: %s\n"
1028 " Is Full Duplex: %s\n"
1029 " Link Speed: %u",
1030 network::IPAddress(&ip.ip).str_to(ip_buf), App.get_name().c_str(),
1031 network::IPAddress(&ip.netmask).str_to(subnet_buf), network::IPAddress(&ip.gw).str_to(gateway_buf),
1032 network::IPAddress(dns_ip1).str_to(dns1_buf), network::IPAddress(dns_ip2).str_to(dns2_buf),
1033 this->get_eth_mac_address_pretty_into_buffer(mac_buf),
1034 YESNO(this->get_duplex_mode() == ETH_DUPLEX_FULL), link_speed);
1035
1036#if USE_NETWORK_IPV6
1037 struct esp_ip6_addr if_ip6s[CONFIG_LWIP_IPV6_NUM_ADDRESSES];
1038 uint8_t count = 0;
1039 count = esp_netif_get_all_ip6(this->eth_netif_, if_ip6s);
1040 assert(count <= CONFIG_LWIP_IPV6_NUM_ADDRESSES);
1041 for (int i = 0; i < count; i++) {
1042 ESP_LOGCONFIG(TAG, " IPv6: " IPV6STR, IPV62STR(if_ip6s[i]));
1043 }
1044#endif /* USE_NETWORK_IPV6 */
1045}
1046
1048 if (!this->ethernet_initialized_) {
1049 // External callers (mdns, ethernet_info, etc.) may ask for the MAC before/regardless
1050 // of whether ethernet is enabled. Use the configured MAC if set, else the system ETH MAC.
1051 if (this->fixed_mac_.has_value()) {
1052 memcpy(mac, this->fixed_mac_->data(), MAC_ADDRESS_SIZE);
1053 } else {
1054 esp_read_mac(mac, ESP_MAC_ETH);
1055 }
1056 return;
1057 }
1058 esp_err_t err;
1059 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_G_MAC_ADDR, mac);
1060 ESPHL_ERROR_CHECK(err, "ETH_CMD_G_MAC error");
1061}
1062
1064 std::span<char, MAC_ADDRESS_PRETTY_BUFFER_SIZE> buf) {
1065 uint8_t mac[MAC_ADDRESS_SIZE];
1067 format_mac_addr_upper(mac, buf.data());
1068 return buf.data();
1069}
1070
1072 if (!this->ethernet_initialized_)
1073 return ETH_DUPLEX_HALF;
1074 esp_err_t err;
1075 eth_duplex_t duplex_mode;
1076 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_G_DUPLEX_MODE, &duplex_mode);
1077 ESPHL_ERROR_CHECK_RET(err, "ETH_CMD_G_DUPLEX_MODE error", ETH_DUPLEX_HALF);
1078 return duplex_mode;
1079}
1080
1082 if (!this->ethernet_initialized_)
1083 return ETH_SPEED_10M;
1084 esp_err_t err;
1086 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_G_SPEED, &speed);
1087 ESPHL_ERROR_CHECK_RET(err, "ETH_CMD_G_SPEED error", ETH_SPEED_10M);
1088 return speed;
1089}
1090
1092 ESP_LOGI(TAG, "Powering down ethernet PHY");
1093 if (this->phy_ == nullptr) {
1094 ESP_LOGE(TAG, "Ethernet PHY not assigned");
1095 return false;
1096 }
1097 this->connected_ = false;
1098 this->started_ = false;
1099 // No need to enable_loop() here as this is only called during shutdown/reboot
1100 if (this->phy_->pwrctl(this->phy_, false) != ESP_OK) {
1101 ESP_LOGE(TAG, "Error powering down ethernet PHY");
1102 return false;
1103 }
1104 return true;
1105}
1106
1107#ifndef USE_ETHERNET_SPI
1108
1109#ifdef USE_ETHERNET_KSZ8081
1110constexpr uint8_t KSZ80XX_PC2R_REG_ADDR = 0x1F;
1111
1113 esp_err_t err;
1114
1115 uint32_t phy_control_2;
1116 err = mac->read_phy_reg(mac, this->phy_addr_, KSZ80XX_PC2R_REG_ADDR, &(phy_control_2));
1117 ESPHL_ERROR_CHECK(err, "Read PHY Control 2 failed");
1118#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
1119 char hex_buf[format_hex_pretty_size(PHY_REG_SIZE)];
1120#endif
1121 ESP_LOGVV(TAG, "KSZ8081 PHY Control 2: %s", format_hex_pretty_to(hex_buf, (uint8_t *) &phy_control_2, PHY_REG_SIZE));
1122
1123 /*
1124 * Bit 7 is `RMII Reference Clock Select`. Default is `0`.
1125 * KSZ8081RNA:
1126 * 0 - clock input to XI (Pin 8) is 25 MHz for RMII - 25 MHz clock mode.
1127 * 1 - clock input to XI (Pin 8) is 50 MHz for RMII - 50 MHz clock mode.
1128 * KSZ8081RND:
1129 * 0 - clock input to XI (Pin 8) is 50 MHz for RMII - 50 MHz clock mode.
1130 * 1 - clock input to XI (Pin 8) is 25 MHz (driven clock only, not a crystal) for RMII - 25 MHz clock mode.
1131 */
1132 if ((phy_control_2 & (1 << 7)) != (1 << 7)) {
1133 phy_control_2 |= 1 << 7;
1134 err = mac->write_phy_reg(mac, this->phy_addr_, KSZ80XX_PC2R_REG_ADDR, phy_control_2);
1135 ESPHL_ERROR_CHECK(err, "Write PHY Control 2 failed");
1136 err = mac->read_phy_reg(mac, this->phy_addr_, KSZ80XX_PC2R_REG_ADDR, &(phy_control_2));
1137 ESPHL_ERROR_CHECK(err, "Read PHY Control 2 failed");
1138 ESP_LOGVV(TAG, "KSZ8081 PHY Control 2: %s",
1139 format_hex_pretty_to(hex_buf, (uint8_t *) &phy_control_2, PHY_REG_SIZE));
1140 }
1141}
1142#endif // USE_ETHERNET_KSZ8081
1143
1144#ifdef ESPHOME_ETHERNET_PHY_REGISTER_COUNT
1145void EthernetComponent::write_phy_register_(esp_eth_mac_t *mac, PHYRegister register_data) {
1146 esp_err_t err;
1147
1148#ifdef USE_ETHERNET_RTL8201
1149 constexpr uint8_t eth_phy_psr_reg_addr = 0x1F;
1150 if (this->type_ == ETHERNET_TYPE_RTL8201 && register_data.page) {
1151 ESP_LOGD(TAG, "Select PHY Register Page: 0x%02" PRIX32, register_data.page);
1152 err = mac->write_phy_reg(mac, this->phy_addr_, eth_phy_psr_reg_addr, register_data.page);
1153 ESPHL_ERROR_CHECK(err, "Select PHY Register page failed");
1154 }
1155#endif
1156
1157 ESP_LOGD(TAG, "Writing PHY reg 0x%02" PRIX32 " = 0x%04" PRIX32, register_data.address, register_data.value);
1158 err = mac->write_phy_reg(mac, this->phy_addr_, register_data.address, register_data.value);
1159 ESPHL_ERROR_CHECK(err, "Writing PHY Register failed");
1160
1161#ifdef USE_ETHERNET_RTL8201
1162 if (this->type_ == ETHERNET_TYPE_RTL8201 && register_data.page) {
1163 ESP_LOGD(TAG, "Select PHY Register Page 0x00");
1164 err = mac->write_phy_reg(mac, this->phy_addr_, eth_phy_psr_reg_addr, 0x0);
1165 ESPHL_ERROR_CHECK(err, "Select PHY Register Page 0 failed");
1166 }
1167#endif
1168}
1169#endif // ESPHOME_ETHERNET_PHY_REGISTER_COUNT
1170
1171#ifdef USE_ETHERNET_YT8531
1173 esp_err_t err;
1174
1175 // The YT8531 disables auto-negotiation on hardware reset (undocumented behavior), and the
1176 // generic 802.3 driver only resets the PHY, so re-enable it (this also updates the driver's
1177 // cached auto-nego state used by esp_eth_start()).
1178 bool autoneg_enable = true;
1179 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_S_AUTONEGO, &autoneg_enable);
1180 ESPHL_ERROR_CHECK(err, "YT8531 enable auto-negotiation failed");
1181
1182 // RGMII needs ~2 ns Tx and Rx clock delays for reliable data sampling. These are set through
1183 // the YT8531 extended-register interface: write the ext-register address to 0x1E, then
1184 // read/modify/write its value via 0x1F.
1185 esp_eth_phy_reg_rw_data_t phy_reg;
1186 uint32_t reg_val;
1187 phy_reg.reg_value_p = &reg_val;
1188
1189 // RX ~2 ns coarse delay: EXT_CHIP_CONFIG (0xA001), set rxc_dly_en (bit 8).
1190 reg_val = 0xA001;
1191 phy_reg.reg_addr = 0x1E;
1192 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_WRITE_PHY_REG, &phy_reg);
1193 ESPHL_ERROR_CHECK(err, "YT8531 select Chip_Config failed");
1194 phy_reg.reg_addr = 0x1F;
1195 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_READ_PHY_REG, &phy_reg);
1196 ESPHL_ERROR_CHECK(err, "YT8531 read Chip_Config failed");
1197 reg_val |= (1U << 8);
1198 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_WRITE_PHY_REG, &phy_reg);
1199 ESPHL_ERROR_CHECK(err, "YT8531 write Chip_Config failed");
1200
1201 // TX ~2 ns delay: EXT_RGMII_CONFIG1 (0xA003), tx_delay_sel[3:0] and tx_delay_sel_fe[7:4] = 13.
1202 reg_val = 0xA003;
1203 phy_reg.reg_addr = 0x1E;
1204 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_WRITE_PHY_REG, &phy_reg);
1205 ESPHL_ERROR_CHECK(err, "YT8531 select RGMII_Config1 failed");
1206 phy_reg.reg_addr = 0x1F;
1207 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_READ_PHY_REG, &phy_reg);
1208 ESPHL_ERROR_CHECK(err, "YT8531 read RGMII_Config1 failed");
1209 reg_val = (reg_val & ~0x00FFU) | (13U << 4) | (13U << 0);
1210 err = esp_eth_ioctl(this->eth_handle_, ETH_CMD_WRITE_PHY_REG, &phy_reg);
1211 ESPHL_ERROR_CHECK(err, "YT8531 write RGMII_Config1 failed");
1212}
1213#endif
1214
1215#endif
1216
1217} // namespace esphome::ethernet
1218
1219#endif // USE_ETHERNET && USE_ESP32
uint8_t status
Definition bl0942.h:8
const StringRef & get_name() const
Get the name of this Application set by pre_setup().
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void mark_failed()
Mark this component as failed.
bool is_failed() const
Definition component.h:287
void enable_loop_soon_any_context()
Thread and ISR-safe version of enable_loop() that can be called from any context.
void enable_loop()
Enable this component's loop.
Definition component.h:261
void disable_loop()
Disable this component's loop.
void status_clear_warning()
Definition component.h:309
Helper class to lock the lwIP TCPIP core when making lwIP API calls from non-TCPIP threads.
Definition helpers.h:2276
constexpr const char * c_str() const
Definition string_ref.h:78
void trigger(const Ts &...x) ESPHOME_ALWAYS_INLINE
Inform the parent automation that the event has triggered.
Definition automation.h:557
StaticVector< PHYRegister, ESPHOME_ETHERNET_PHY_REGISTER_COUNT > phy_registers_
static void got_ip_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
void yt8531_phy_init_()
Apply YT8531-specific config: re-enable auto-negotiation (disabled on reset) and set the RGMII Tx/Rx ...
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 ksz8081_set_clock_reference_(esp_eth_mac_t *mac)
Set RMII Reference Clock Select bit for KSZ8081.
optional< std::array< uint8_t, MAC_ADDRESS_SIZE > > fixed_mac_
static void eth_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
const char * get_eth_mac_address_pretty_into_buffer(std::span< char, MAC_ADDRESS_PRETTY_BUFFER_SIZE > buf)
SPIInterface get_interface() const
Definition spi.h:368
const LogString * message
Definition component.cpp:35
eth_esp32_emac_config_t eth_esp32_emac_default_config(void)
int speed
Definition fan.h:3
bool state
Definition fan.h:2
unsigned count
Definition gif.cpp:51
uint32_t buffer
Definition gif.cpp:50
ESPHOME_LOG_TAG(TAG, "ethernet")
constexpr uint8_t KSZ80XX_PC2R_REG_ADDR
void install_w5500_async_spi(eth_w5500_config_t &config)
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:368
void fill_ip6_addresses(esp_netif_t *netif, IPAddresses &addresses)
Copies the IPv6 addresses of an esp_netif into addresses[1..], warning once when some do not fit.
Definition util.cpp:13
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:498
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:1687
void HOT delay(uint32_t ms)
Definition hal.cpp:85
uint32_t IRAM_ATTR HOT millis()
Definition hal.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:1754
struct esp_netif_obj esp_netif_t
static void uint32_t
network::IPAddress dns1
The first DNS server. 0.0.0.0 for default.
network::IPAddress dns2
The second DNS server. 0.0.0.0 for default.
char * str_to(char *buf) const
Definition ip_address.h:152
uint16_t length
Definition tt21100.cpp:0
uint8_t event_id
Definition tt21100.cpp:3
SemaphoreHandle_t lock
spi_device_handle_t handle