3#if !defined(USE_ESP32) && !defined(USE_ESP8266) && !defined(USE_RP2) && !defined(USE_LIBRETINY) && \
4 (defined(USE_SOCKET_IMPL_LWIP_SOCKETS) || defined(USE_SOCKET_IMPL_BSD_SOCKETS))
16static constexpr size_t READ_BUFFER_SIZE = 1460;
19 if (connected_ || connecting_) {
20 ESP_LOGW(TAG,
"Already connected/connecting");
28 ESP_LOGE(TAG,
"Invalid address: %s", host);
30 error_cb_(error_arg_,
this, -1);
35 int family = ((
struct sockaddr *) &addr)->sa_family;
38 ESP_LOGE(TAG,
"Failed to create socket");
40 error_cb_(error_arg_,
this, -1);
44 if (socket_->setblocking(
false) != 0) {
46 const int saved_errno = errno;
47 ESP_LOGE(TAG,
"Failed to set nonblocking: errno %d", saved_errno);
50 error_cb_(error_arg_,
this, saved_errno);
54 int err = socket_->connect((
struct sockaddr *) &addr, addrlen);
59 connect_cb_(connect_arg_,
this);
62 const int saved_errno = errno;
63 if (saved_errno != EINPROGRESS) {
64 ESP_LOGE(TAG,
"Connect failed: %d", saved_errno);
67 error_cb_(error_arg_,
this, saved_errno);
77 bool was_connected = connected_;
80 if (was_connected && disconnect_cb_)
81 disconnect_cb_(disconnect_arg_,
this);
85 if (!socket_ || !connected_)
90 const int err = errno;
91 if (err != EAGAIN && err != EWOULDBLOCK) {
92 ESP_LOGE(TAG,
"Write error: %d", err);
95 error_cb_(error_arg_,
this, err);
115 connect_cb_(connect_arg_,
this);
118 ESP_LOGW(TAG,
"Connection failed: %d", err);
121 error_cb_(error_arg_,
this, err);
124 }
else if (connected_) {
126 if (!socket_->ready())
129 uint8_t buf[READ_BUFFER_SIZE];
130 ssize_t len = socket_->read(buf, READ_BUFFER_SIZE);
133 ESP_LOGI(TAG,
"Connection closed by peer");
135 }
else if (
len > 0) {
137 data_cb_(data_arg_,
this, buf,
len);
139 const int err = errno;
140 if (err != EAGAIN && err != EWOULDBLOCK) {
141 ESP_LOGW(TAG,
"Read error: %d", err);
144 error_cb_(error_arg_,
this, err);
bool connect(const char *host, uint16_t port)
size_t write(const char *data, size_t len)
ESPHOME_LOG_TAG(TAG, "async_tcp")
ConnectPollResult poll_connect(Socket &sock, int &err_out)
Poll a connect() that returned EINPROGRESS.
socklen_t set_sockaddr(struct sockaddr *addr, socklen_t addrlen, const char *ip_address, uint16_t port)
Set a sockaddr to the specified address and port for the IP version used by socket_ip().
@ CONNECT_POLL_RESULT_CONNECTED
@ CONNECT_POLL_RESULT_ERROR
@ CONNECT_POLL_RESULT_PENDING
std::unique_ptr< Socket > socket_loop_monitored(int domain, int type, int protocol)
Create a socket and monitor it for data in the main loop.