ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
tcp_client_link.h
Go to the documentation of this file.
1#pragma once
2
3#include "headers.h"
4
5#if defined(USE_SOCKET_IMPL_LWIP_TCP) || defined(USE_SOCKET_IMPL_LWIP_SOCKETS) || defined(USE_SOCKET_IMPL_BSD_SOCKETS)
6
7#include "ipv4_resolve.h"
8#include "socket.h"
10#include "esphome/core/log.h"
12
13#include <cstdint>
14#include <memory>
15
16namespace esphome::socket {
17
23 public:
24 void set_host(const char *host) { this->host_ = StringRef(host); }
25 void set_port(uint16_t port) { this->port_ = port; }
30 const char *host() const { return this->host_.c_str(); }
31 uint16_t port() const { return this->port_; }
33 uint32_t idle_timeout() const { return this->idle_timeout_ms_; }
34
36 void begin(const char *tag);
39 void poll() {
40 if (this->connected_ || (this->sock_ == nullptr && this->in_backoff())) {
41 return;
42 }
43 this->poll_slow_();
44 }
46 void adopt(std::unique_ptr<Socket> sock);
48 ssize_t read(uint8_t *buf, size_t len);
50 size_t queue(const uint8_t *data, size_t len);
53 uint8_t *tx_tail() { return this->tx_ + this->tx_len_; }
54 void tx_commit(size_t len) { this->tx_len_ += static_cast<uint16_t>(len); }
55 size_t tx_free() const { return this->connected_ ? TX_BUFFER_SIZE - this->tx_len_ : 0; }
58 bool flush_tx() {
59 if (this->tx_len_ != 0) {
60 this->flush_tx_slow_();
61 }
62 return this->tx_len_ == 0;
63 }
65 void close();
70 void check_idle() {
71 if (this->idle_timeout_ms_ != 0 && this->connected_ &&
72 App.get_loop_component_start_time() - this->last_io_ms_ >= this->idle_timeout_ms_) {
73 this->idle_close_();
74 }
75 }
76
77 bool connected() const { return this->connected_; }
79 bool connecting() const { return this->sock_ != nullptr && !this->connected_; }
80 bool ready() const { return this->sock_ != nullptr && this->sock_->ready(); }
86
87 protected:
88 static constexpr size_t TX_BUFFER_SIZE = 1024;
89
91 ssize_t write_(const uint8_t *buf, size_t len);
92 void flush_tx_slow_();
93 void poll_slow_();
94 void try_connect_();
96 void drop_(const LogString *what, int err);
98 void idle_close_();
99
101 std::unique_ptr<Socket> sock_;
102 const char *tag_{nullptr};
108 uint16_t port_{0};
109 uint16_t tx_len_{0};
110 bool connected_{false};
111 uint8_t tx_[TX_BUFFER_SIZE]{};
112};
113
114} // namespace esphome::socket
115
116#endif
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.
StringRef is a reference to a string owned by something else.
Definition string_ref.h:31
constexpr const char * c_str() const
Definition string_ref.h:78
One IPv4 literal or hostname. Must outlive a pending lookup.
__int64 ssize_t
Definition httplib.h:178
const void size_t len
Definition hal.h:68
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t