ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
tcp_packet_interface.cpp
Go to the documentation of this file.
4#include "esphome/core/log.h"
5
6namespace esphome::tcp {
7
10
11ESPHOME_LOG_TAG(TAG, "tcp.packet_interface");
12
13// The packet length before each packet
14static constexpr size_t LENGTH_SIZE = 2;
15// A peer that sends without a pause must not hold the main loop here; a frame being read carries over to the next pass
16static constexpr uint8_t MAX_FRAMES_PER_LOOP = 8;
17
18TcpPacketInterface::TcpPacketInterface(std::span<uint8_t> rx_buffer)
19 : packet_interface::PacketInterface(rx_buffer.size()), rx_buffer_(rx_buffer) {
22}
23
25 this->link_.begin(TAG);
26#ifdef USE_SOCKET_TCP_LISTENER
27 this->listener_.begin(TAG);
28#endif
29#ifdef USE_BINARY_SENSOR
30 if (this->connected_binary_sensor_ != nullptr)
31 this->connected_binary_sensor_->publish_initial_state(false);
32#endif
33}
34
36 bool server = false;
37#ifdef USE_SOCKET_TCP_LISTENER
38 server = this->server_;
39#endif
40 ESP_LOGCONFIG(TAG,
41 "TCP Packet Interface '%s':\n"
42 " Role: %s\n"
43 " Address: %s:%u\n"
44 " Reconnect Interval: %" PRIu32 "ms\n"
45 " Keep Alive: %" PRIu32 "ms\n"
46 " Timeout: %" PRIu32 "ms\n"
47 " Max Packet Size: %zu",
48 this->name_, server ? LOG_STR_LITERAL("server") : LOG_STR_LITERAL("client"),
49 server ? LOG_STR_LITERAL("*") : this->link_.host(), this->link_.port(),
50 this->link_.reconnect_interval(), this->keep_alive_ms_, this->timeout_ms_, this->max_packet_size_);
51#ifdef USE_SOCKET_TCP_LISTENER
52 this->listener_.dump_config();
53#endif
54#ifdef USE_BINARY_SENSOR
55 LOG_BINARY_SENSOR(" ", "Connected", this->connected_binary_sensor_);
56#endif
57}
58
60 this->link_.close();
61#ifdef USE_SOCKET_TCP_LISTENER
62 this->listener_.close();
63#endif
64}
65
67#ifdef USE_SOCKET_TCP_LISTENER
68 if (this->server_) {
69 // A new client is accepted only once the drop of the last has been reported
70 this->listener_.poll(this->link_, !this->connected_);
71 } else {
72 this->link_.poll();
73 }
74#else
75 this->link_.poll();
76#endif
77 if (this->link_.connected() != this->connected_)
78 this->on_connection_(this->link_.connected());
79 if (!this->connected_)
80 return;
81 this->read_();
82 if (!this->connected_)
83 return;
85 if (now - this->last_rx_ms_ > this->timeout_ms_) {
86 ESP_LOGW(TAG, "%s: Nothing received for %" PRIu32 "ms, closing the connection", this->name_, this->timeout_ms_);
87 this->link_.close();
88 this->link_.note_attempt();
89 this->on_connection_(false);
90 return;
91 }
92 if (now - this->last_tx_ms_ >= this->keep_alive_ms_)
93 this->queue_frame_(nullptr, 0);
94 this->flush_();
95}
96
98
100 if (!this->tx_waiting_)
101 return SIZE_MAX;
102 return this->link_.tx_free() / (this->max_packet_size_ + LENGTH_SIZE);
103}
104
106 ESP_LOGD(TAG, "%s: Connection %s", this->name_, connected ? LOG_STR_LITERAL("up") : LOG_STR_LITERAL("down"));
107 this->connected_ = connected;
108 this->tx_waiting_ = false;
109 this->rx_have_ = 0;
111#ifdef USE_BINARY_SENSOR
112 PUBLISH_STATE(this->connected_binary_sensor_, connected);
113#endif
114 this->session_callback_.call(connected);
115}
116
118 for (uint8_t frames = 0; frames != MAX_FRAMES_PER_LOOP;) {
120 if (this->rx_have_ < LENGTH_SIZE) {
121 count = this->link_.read(this->rx_header_ + this->rx_have_, LENGTH_SIZE - this->rx_have_);
122 } else {
123 count = this->link_.read(this->rx_buffer_.data() + this->rx_have_ - LENGTH_SIZE,
124 this->rx_length_ + LENGTH_SIZE - this->rx_have_);
125 }
126 // Nothing more for now; a dropped link is seen on the next loop
127 if (count <= 0)
128 return;
130 this->rx_have_ += count;
131 if (this->rx_have_ < LENGTH_SIZE)
132 continue;
133 if (this->rx_have_ == LENGTH_SIZE) {
135 if (this->rx_length_ > this->max_packet_size_) {
136 // The stream cannot be resynchronised, so start a new connection
137 ESP_LOGW(TAG, "%s: Packet of %u bytes is larger than %zu, closing the connection", this->name_,
138 this->rx_length_, this->max_packet_size_);
139 this->link_.close();
140 this->link_.note_attempt();
141 this->on_connection_(false);
142 return;
143 }
144 }
145 if (this->rx_have_ == this->rx_length_ + LENGTH_SIZE) {
146 this->rx_have_ = 0;
147 frames++;
148 // A zero length packet is a keep-alive
149 if (this->rx_length_ != 0)
150 this->on_receive_from_interface_(PacketBuffer(this->rx_buffer_.data(), this->rx_length_), {});
151 }
152 }
153}
154
156 if (this->link_.tx_free() < size + LENGTH_SIZE)
157 return false;
158 uint8_t *tail = this->link_.tx_tail();
159 put_le16(tail, size);
160 if (data != nullptr)
161 data->copy_to(tail + LENGTH_SIZE, size);
162 this->link_.tx_commit(size + LENGTH_SIZE);
164 return true;
165}
166
168 size_t size = data.size();
169 if (size > this->max_packet_size_) {
170 ESP_LOGW(TAG, "%s: Packet of %zu bytes is larger than %zu", this->name_, size, this->max_packet_size_);
171 return false;
172 }
173 if (!this->connected_ || !this->queue_frame_(&data, size))
174 return false;
175 // A write that fails closes the link and discards what was queued, this packet included
176 this->flush_();
177 return this->link_.connected();
178}
179
180} // namespace esphome::tcp
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.
A buffer class that efficiently represents a composite buffer with three sections:
LazyCallbackManager< void(bool)> session_callback_
void on_receive_from_interface_(const PacketBuffer &data, const PacketMetaData &meta_data)
This function should be called by implementing classes with received data to be passed to any listene...
A struct to hold metadata about a packet.
void begin(const char *tag)
Call from setup(); tag names the log lines.
void dump_config() const
One config line per allowed network.
void poll(TcpClientLinkBase &link, bool may_accept)
Server state machine; call every loop.
bool queue_frame_(const packet_interface::PacketBuffer *data, size_t size)
size_t get_send_capacity() const override
Unlimited while the socket takes what is sent.
bool send_to_interface(const packet_interface::PacketBuffer &data, const packet_interface::PacketMetaData &meta_data) override
const std::span< uint8_t > rx_buffer_
TcpPacketInterface(std::span< uint8_t > rx_buffer)
unsigned count
Definition gif.cpp:51
__int64 ssize_t
Definition httplib.h:178
ESPHOME_LOG_TAG(TAG, "tcp.packet_interface")
uint16_t size
Definition helpers.cpp:44
constexpr T encode_value_le(const uint8_t *bytes)
Encode a value from its constituent bytes (from least to most significant) in an array with length si...
Definition helpers.h:1268
Application App
Global storage of Application pointer - only one Application can exist.
constexpr uint8_t * put_le16(uint8_t *dst, uint16_t value)
Definition helpers.h:1314
static void uint32_t
httpd_handle_t server