diff --git a/esphome/components/socket/bsd_sockets_impl.cpp b/esphome/components/socket/bsd_sockets_impl.cpp index 2d4e0ea7c2..d55523ff77 100644 --- a/esphome/components/socket/bsd_sockets_impl.cpp +++ b/esphome/components/socket/bsd_sockets_impl.cpp @@ -14,13 +14,8 @@ BSDSocketImpl::BSDSocketImpl(int fd, bool monitor_loop) { if (!monitor_loop || this->fd_ < 0) return; #ifdef USE_LWIP_FAST_SELECT - // Cache lwip_sock pointer (used by ready() for direct rcvevent reads) and hook the - // netconn event callback so the main loop is notified via FreeRTOS task notifications. - this->cached_sock_ = esphome_lwip_get_sock(this->fd_); - if (this->cached_sock_ != nullptr) { - esphome_lwip_hook_socket(this->cached_sock_); - this->loop_monitored_ = true; - } + this->cached_sock_ = fast_select_hook_fd(this->fd_); + this->loop_monitored_ = this->cached_sock_ != nullptr; #else this->loop_monitored_ = App.register_socket_fd(this->fd_); #endif diff --git a/esphome/components/socket/lwip_sockets_impl.cpp b/esphome/components/socket/lwip_sockets_impl.cpp index c65d3a227d..475381548b 100644 --- a/esphome/components/socket/lwip_sockets_impl.cpp +++ b/esphome/components/socket/lwip_sockets_impl.cpp @@ -14,13 +14,8 @@ LwIPSocketImpl::LwIPSocketImpl(int fd, bool monitor_loop) { if (!monitor_loop || this->fd_ < 0) return; #ifdef USE_LWIP_FAST_SELECT - // Cache lwip_sock pointer (used by ready() for direct rcvevent reads) and hook the - // netconn event callback so the main loop is notified via FreeRTOS task notifications. - this->cached_sock_ = esphome_lwip_get_sock(this->fd_); - if (this->cached_sock_ != nullptr) { - esphome_lwip_hook_socket(this->cached_sock_); - this->loop_monitored_ = true; - } + this->cached_sock_ = fast_select_hook_fd(this->fd_); + this->loop_monitored_ = this->cached_sock_ != nullptr; #else this->loop_monitored_ = App.register_socket_fd(this->fd_); #endif diff --git a/esphome/components/socket/socket.h b/esphome/components/socket/socket.h index ad55e889e8..c33a5c42b6 100644 --- a/esphome/components/socket/socket.h +++ b/esphome/components/socket/socket.h @@ -45,6 +45,17 @@ using ListenSocket = LWIPRawListenImpl; inline bool socket_ready(struct lwip_sock *cached_sock, bool loop_monitored) { return !loop_monitored || (cached_sock != nullptr && esphome_lwip_socket_has_data(cached_sock)); } + +/// Resolve an fd to its lwip_sock and hook the netconn event callback so the main loop +/// is woken by FreeRTOS task notifications. Shared between BSD and LwIP socket impls. +/// Returns the cached lwip_sock pointer (or nullptr if fd is invalid). +inline struct lwip_sock *fast_select_hook_fd(int fd) { + struct lwip_sock *sock = esphome_lwip_get_sock(fd); + if (sock != nullptr) { + esphome_lwip_hook_socket(sock); + } + return sock; +} #elif defined(USE_HOST) /// Shared ready() helper for fd-based socket implementations. /// Checks if the Application's select() loop has marked this fd as ready.