@@ -281,6 +281,7 @@ bool ETHClass::begin(eth_phy_type_t type, int32_t phy_addr, int mdc, int mdio, i
281281 _mac = esp_eth_mac_new_esp32 (&mac_config, ð_mac_config);
282282 if (_mac == NULL ) {
283283 log_e (" esp_eth_mac_new_esp32 failed" );
284+ _delMacAndPhy ();
284285 return false ;
285286 }
286287
@@ -305,6 +306,7 @@ bool ETHClass::begin(eth_phy_type_t type, int32_t phy_addr, int mdc, int mdio, i
305306 }
306307 if (_phy == NULL ) {
307308 log_e (" esp_eth_phy_new failed" );
309+ _delMacAndPhy ();
308310 return false ;
309311 }
310312
@@ -738,15 +740,29 @@ bool ETHClass::beginSPI(
738740 return false ;
739741 }
740742
743+ if (_mac == NULL ) {
744+ log_e (" esp_eth_mac_new failed" );
745+ _delMacAndPhy ();
746+ return false ;
747+ }
748+
749+ if (_phy == NULL ) {
750+ log_e (" esp_eth_phy_new failed" );
751+ _delMacAndPhy ();
752+ return false ;
753+ }
754+
741755 // Init Ethernet driver to default and install it
742756 esp_eth_config_t eth_config = ETH_DEFAULT_CONFIG (_mac, _phy);
743757 ret = esp_eth_driver_install (ð_config, &_eth_handle);
744758 if (ret != ESP_OK) {
745759 log_e (" SPI Ethernet driver install failed: %d" , ret);
760+ _delMacAndPhy ();
746761 return false ;
747762 }
748763 if (_eth_handle == NULL ) {
749764 log_e (" esp_eth_driver_install failed! eth_handle is NULL" );
765+ _delMacAndPhy ();
750766 return false ;
751767 }
752768
@@ -923,6 +939,18 @@ static bool empty_ethDetachBus(void *bus_pointer) {
923939 return true ;
924940}
925941
942+ void ETHClass::_delMacAndPhy () {
943+ if (_mac != NULL ) {
944+ _mac->del (_mac);
945+ _mac = NULL ;
946+ }
947+
948+ if (_phy != NULL ) {
949+ _phy->del (_phy);
950+ _phy = NULL ;
951+ }
952+ }
953+
926954void ETHClass::end (void ) {
927955
928956 Network.removeEvent (_eth_connected_event_handle);
@@ -954,18 +982,10 @@ void ETHClass::end(void) {
954982 return ;
955983 }
956984 _eth_handle = NULL ;
957- // delete mac
958- if (_mac != NULL ) {
959- _mac->del (_mac);
960- _mac = NULL ;
961- }
962- // delete phy
963- if (_phy != NULL ) {
964- _phy->del (_phy);
965- _phy = NULL ;
966- }
967985 }
968986
987+ _delMacAndPhy ();
988+
969989 if (_eth_ev_instance != NULL ) {
970990 bool do_not_unreg_ev_handler = false ;
971991 for (int i = 0 ; i < NUM_SUPPORTED_ETH_PORTS; ++i) {
0 commit comments