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