diff --git a/esphome/components/socket/bsd_sockets_impl.cpp b/esphome/components/socket/bsd_sockets_impl.cpp index 51b75a1057..99a790912c 100644 --- a/esphome/components/socket/bsd_sockets_impl.cpp +++ b/esphome/components/socket/bsd_sockets_impl.cpp @@ -42,6 +42,7 @@ std::string format_sockaddr(const struct sockaddr_storage &storage) { class BSDSocketImpl : public Socket { public: BSDSocketImpl(int fd, bool monitor_loop = false) : fd_(fd) { + monitored_ = monitor_loop; // Register new socket with the application for select() if monitoring requested if (monitor_loop && fd_ >= 0) { App.register_socket_fd(fd_); @@ -57,7 +58,7 @@ class BSDSocketImpl : public Socket { int fd = ::accept(fd_, addr, addrlen); if (fd == -1) return {}; - return make_unique(fd); // Default: not monitored + return make_unique(fd); } std::unique_ptr accept_monitored(struct sockaddr *addr, socklen_t *addrlen) override { int fd = ::accept(fd_, addr, addrlen); @@ -68,8 +69,10 @@ class BSDSocketImpl : public Socket { int bind(const struct sockaddr *addr, socklen_t addrlen) override { return ::bind(fd_, addr, addrlen); } int close() override { if (!closed_) { - // Unregister from select() before closing - App.unregister_socket_fd(fd_); + // Unregister from select() before closing if monitored + if (monitored_) { + App.unregister_socket_fd(fd_); + } int ret = ::close(fd_); closed_ = true; return ret; diff --git a/esphome/components/socket/lwip_sockets_impl.cpp b/esphome/components/socket/lwip_sockets_impl.cpp index 7b946a1dc2..f87a282c32 100644 --- a/esphome/components/socket/lwip_sockets_impl.cpp +++ b/esphome/components/socket/lwip_sockets_impl.cpp @@ -35,6 +35,7 @@ std::string format_sockaddr(const struct sockaddr_storage &storage) { class LwIPSocketImpl : public Socket { public: LwIPSocketImpl(int fd, bool monitor_loop = false) : fd_(fd) { + monitored_ = monitor_loop; // Register new socket with the application for select() if monitoring requested if (monitor_loop && fd_ >= 0) { App.register_socket_fd(fd_); @@ -61,8 +62,10 @@ class LwIPSocketImpl : public Socket { int bind(const struct sockaddr *addr, socklen_t addrlen) override { return lwip_bind(fd_, addr, addrlen); } int close() override { if (!closed_) { - // Unregister from select() before closing - App.unregister_socket_fd(fd_); + // Unregister from select() before closing if monitored + if (monitored_) { + App.unregister_socket_fd(fd_); + } int ret = lwip_close(fd_); closed_ = true; return ret; diff --git a/esphome/components/socket/socket.h b/esphome/components/socket/socket.h index 3afde68fa9..f5e7d6cdc8 100644 --- a/esphome/components/socket/socket.h +++ b/esphome/components/socket/socket.h @@ -52,6 +52,9 @@ class Socket { /// Get the underlying file descriptor (returns -1 if not supported) virtual int get_fd() const { return -1; } + + protected: + bool monitored_{false}; ///< Whether this socket is monitored by the event loop }; /// Create a socket of the given domain, type and protocol.