ESPHome 2026.8.0b4
Loading...
Searching...
No Matches
serial_proxy.cpp
Go to the documentation of this file.
1#include "serial_proxy.h"
2
3#ifdef USE_SERIAL_PROXY
4
5#include "esphome/core/log.h"
6
7#include <cinttypes>
8#include "esphome/core/util.h"
9
10#ifdef USE_API
13#endif
14
16
17static const char *const TAG = "serial_proxy";
18
20 // Set up modem control pins if configured
21 if (this->rts_pin_ != nullptr) {
22 this->rts_pin_->setup();
23 this->rts_pin_->digital_write(this->rts_state_);
24 }
25 if (this->dtr_pin_ != nullptr) {
26 this->dtr_pin_->setup();
27 this->dtr_pin_->digital_write(this->dtr_state_);
28 }
29#ifdef USE_API
30 // instance_index_ is fixed at registration time; pre-set it so loop() only needs to update data
32#endif
33 // No subscriber at startup; disable loop until a client subscribes
34 this->disable_loop();
35}
36
38#ifdef USE_API
39 // Safety check — loop should only run when subscribed, but guard against races
40 if (this->api_connection_ == nullptr) [[unlikely]] {
41 this->disable_loop();
42 return;
43 }
44
45 // Detect subscriber disconnect
46 if (this->api_connection_->is_marked_for_removal() || !this->api_connection_->is_connection_setup() ||
48 ESP_LOGW(TAG, "Subscriber disconnected");
49 this->api_connection_ = nullptr;
50 this->disable_loop();
51 return;
52 }
53
54 // Read available data from UART and forward to subscribed client
55 size_t available = this->available();
56 if (available == 0)
57 return;
58
59 this->read_and_send_(available);
60#endif
61}
62
63#ifdef USE_API
64void __attribute__((noinline)) SerialProxy::read_and_send_(size_t available) {
65 // Read in chunks up to SERIAL_PROXY_MAX_READ_SIZE
66 uint8_t buffer[SERIAL_PROXY_MAX_READ_SIZE];
67 size_t to_read = std::min(available, sizeof(buffer));
68
69 if (!this->read_array(buffer, to_read))
70 return;
71
72 this->outgoing_msg_.set_data(buffer, to_read);
74}
75#endif
76
78 ESP_LOGCONFIG(TAG,
79 "Serial Proxy [%" PRIu32 "]:\n"
80 " Name: %s\n"
81 " Port Type: %s\n"
82 " RTS Pin: %s\n"
83 " DTR Pin: %s",
84 this->instance_index_, this->name_ != nullptr ? this->name_ : "",
87 : "TTL",
88 this->rts_pin_ != nullptr ? "configured" : "not configured",
89 this->dtr_pin_ != nullptr ? "configured" : "not configured");
90}
91
92void SerialProxy::configure(api::APIConnection *api_connection, uint32_t baudrate, bool flow_control, uint8_t parity,
93 uint8_t stop_bits, uint8_t data_size) {
94#ifdef USE_API
95 if (this->port_claimed_by_other_(api_connection)) {
96 ESP_LOGW(TAG, "Ignoring configure request from client without port access [%" PRIu32 "]", this->instance_index_);
97 return;
98 }
99#endif
100 ESP_LOGD(TAG,
101 "Configuring serial proxy [%" PRIu32 "]: baud=%" PRIu32 ", flow_ctrl=%s, parity=%" PRIu8 ", stop=%" PRIu8
102 ", data=%" PRIu8,
103 this->instance_index_, baudrate, YESNO(flow_control), parity, stop_bits, data_size);
104
105 auto *uart_comp = this->parent_;
106 if (uart_comp == nullptr) {
107 ESP_LOGE(TAG, "UART component not available");
108 return;
109 }
110
111 // Validate all parameters before applying any (values come from a remote client)
112 if (baudrate == 0) {
113 ESP_LOGW(TAG, "Invalid baud rate: 0");
114 return;
115 }
116 if (stop_bits < 1 || stop_bits > 2) {
117 ESP_LOGW(TAG, "Invalid stop bits: %u (must be 1 or 2)", stop_bits);
118 return;
119 }
120 if (data_size < 5 || data_size > 8) {
121 ESP_LOGW(TAG, "Invalid data bits: %u (must be 5-8)", data_size);
122 return;
123 }
124 if (parity > 2) {
125 ESP_LOGW(TAG, "Invalid parity: %u (must be 0-2)", parity);
126 return;
127 }
128
129 // Apply validated parameters
130 uart_comp->set_baud_rate(baudrate);
131 uart_comp->set_stop_bits(stop_bits);
132 uart_comp->set_data_bits(data_size);
133
134 // Map parity value to UARTParityOptions
135 static const uart::UARTParityOptions PARITY_MAP[] = {
139 };
140 uart_comp->set_parity(PARITY_MAP[parity]);
141
142 // load_settings() is available on ESP8266 and ESP32 platforms
143#if defined(USE_ESP8266) || defined(USE_ESP32)
144 uart_comp->load_settings(true);
145#endif
146
147 if (flow_control) {
148 ESP_LOGW(TAG, "Hardware flow control requested but is not yet supported");
149 }
150}
151
152void SerialProxy::write_from_client(api::APIConnection *api_connection, const uint8_t *data, size_t len) {
153#ifdef USE_API
154 // Bytes from a client other than the live subscriber would interleave with the
155 // subscriber's traffic on the wire
156 if (this->port_claimed_by_other_(api_connection)) {
157 ESP_LOGW(TAG, "Ignoring write from client without port access [%" PRIu32 "]", this->instance_index_);
158 return;
159 }
160#endif
161 if (data == nullptr || len == 0)
162 return;
163 this->write_array(data, len);
164}
165
166void SerialProxy::set_modem_pins(api::APIConnection *api_connection, uint32_t line_states) {
167#ifdef USE_API
168 if (this->port_claimed_by_other_(api_connection)) {
169 ESP_LOGW(TAG, "Ignoring modem pin request from client without port access [%" PRIu32 "]", this->instance_index_);
170 return;
171 }
172#endif
173 const bool rts = (line_states & SERIAL_PROXY_LINE_STATE_FLAG_RTS) != 0;
174 const bool dtr = (line_states & SERIAL_PROXY_LINE_STATE_FLAG_DTR) != 0;
175 ESP_LOGV(TAG, "Setting modem pins [%" PRIu32 "]: RTS=%s, DTR=%s", this->instance_index_, ONOFF(rts), ONOFF(dtr));
176
177 if (this->rts_pin_ != nullptr) {
178 this->rts_state_ = rts;
179 this->rts_pin_->digital_write(rts);
180 }
181 if (this->dtr_pin_ != nullptr) {
182 this->dtr_state_ = dtr;
183 this->dtr_pin_->digital_write(dtr);
184 }
185}
186
188 return (this->rts_state_ ? static_cast<uint32_t>(SERIAL_PROXY_LINE_STATE_FLAG_RTS) : 0u) |
189 (this->dtr_state_ ? static_cast<uint32_t>(SERIAL_PROXY_LINE_STATE_FLAG_DTR) : 0u);
190}
191
193 ESP_LOGV(TAG, "Flushing serial proxy [%" PRIu32 "]", this->instance_index_);
194 return this->flush();
195}
196
197#ifdef USE_API
199 return this->api_connection_ != nullptr && this->api_connection_ != api_connection &&
201}
202
204 switch (type) {
206 if (this->api_connection_ == api_connection) {
207 ESP_LOGV(TAG, "API connection is already subscribed to serial proxy [%" PRIu32 "]", this->instance_index_);
208 return;
209 }
210 if (this->api_connection_ != nullptr) {
211 // A living subscriber keeps exclusive access. Its connection may be dead without
212 // loop() having noticed yet (e.g. the client crashed and reconnected quickly);
213 // in that case let the new client take over instead of locking it out.
215 ESP_LOGE(TAG, "Only one API subscription is allowed at a time");
216 return;
217 }
218 ESP_LOGW(TAG, "Previous subscriber disconnected; taking over subscription");
219 }
220 this->api_connection_ = api_connection;
221 this->enable_loop();
222 ESP_LOGV(TAG, "API connection subscribed to serial proxy [%" PRIu32 "]", this->instance_index_);
223 break;
225 if (this->api_connection_ != api_connection) {
226 ESP_LOGV(TAG, "API connection is not subscribed to serial proxy [%" PRIu32 "]", this->instance_index_);
227 return;
228 }
229 this->api_connection_ = nullptr;
230 this->disable_loop();
231 ESP_LOGV(TAG, "API connection unsubscribed from serial proxy [%" PRIu32 "]", this->instance_index_);
232 break;
233 default:
234 ESP_LOGW(TAG, "Unknown serial proxy request type: %" PRIu32, static_cast<uint32_t>(type));
235 break;
236 }
237}
238#endif
239
240} // namespace esphome::serial_proxy
241
242#endif // USE_SERIAL_PROXY
void enable_loop()
Enable this component's loop.
Definition component.h:246
void disable_loop()
Disable this component's loop.
virtual void setup()=0
virtual void digital_write(bool value)=0
void send_serial_proxy_data(const SerialProxyDataReceived &msg)
void set_data(const uint8_t *data, size_t len)
Definition api_pb2.h:3253
void set_modem_pins(api::APIConnection *api_connection, uint32_t line_states)
Set modem pin states from a bitmask of SerialProxyLineStateFlag values.
void read_and_send_(size_t available)
Read from UART and send to API client (slow path with 256-byte stack buffer)
void configure(api::APIConnection *api_connection, uint32_t baudrate, bool flow_control, uint8_t parity, uint8_t stop_bits, uint8_t data_size)
Configure UART parameters and apply them.
uint32_t get_modem_pins() const
Get current modem pin states as a bitmask of SerialProxyLineStateFlag values.
uint32_t instance_index_
Instance index for identifying this proxy in API messages.
bool port_claimed_by_other_(api::APIConnection *api_connection) const
True when a live subscriber other than the given connection holds the port.
bool rts_state_
Current modem pin states.
void serial_proxy_request(api::APIConnection *api_connection, api::enums::SerialProxyRequestType type)
Handle a subscribe/unsubscribe request from an API client.
api::SerialProxyDataReceived outgoing_msg_
Pre-allocated outgoing message; instance field is set once in setup()
const char * name_
Human-readable port name (points to a string literal in flash)
api::enums::SerialProxyPortType port_type_
Port type.
GPIOPin * rts_pin_
Optional GPIO pins for modem control.
uart::UARTFlushResult flush_port()
Flush the serial port (block until all TX data is sent)
void write_from_client(api::APIConnection *api_connection, const uint8_t *data, size_t len)
Write data received from an API client to the serial device.
api::APIConnection * api_connection_
Subscribed API client (only one allowed at a time)
void set_baud_rate(uint32_t baud_rate)
UARTFlushResult flush()
Definition uart.h:48
optional< std::array< uint8_t, N > > read_array()
Definition uart.h:38
UARTComponent * parent_
Definition uart.h:73
void write_array(const uint8_t *data, size_t len)
Definition uart.h:26
struct @66::@67 __attribute__
Wake the main loop task from an ISR. ISR-safe.
Definition main_task.h:32
uint16_t type
@ SERIAL_PROXY_PORT_TYPE_RS232
Definition api_pb2.h:20
@ SERIAL_PROXY_PORT_TYPE_RS485
Definition api_pb2.h:21
@ SERIAL_PROXY_REQUEST_TYPE_UNSUBSCRIBE
Definition api_pb2.h:346
@ SERIAL_PROXY_REQUEST_TYPE_SUBSCRIBE
Definition api_pb2.h:345
@ SERIAL_PROXY_LINE_STATE_FLAG_RTS
RTS (Request To Send)
@ SERIAL_PROXY_LINE_STATE_FLAG_DTR
DTR (Data Terminal Ready)
constexpr size_t SERIAL_PROXY_MAX_READ_SIZE
Maximum bytes to read from UART in a single loop iteration.
UARTFlushResult
Result of a flush() call.
const void size_t len
Definition hal.h:64
ESPHOME_ALWAYS_INLINE bool api_is_connected()
Return whether the node has at least one client connected to the native API.
Definition util.h:20
static void uint32_t