ESPHome 2026.11.0b6
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
6#include "esphome/core/log.h"
7
8#include <algorithm>
9#include <cinttypes>
10#include "esphome/core/util.h"
11
12#ifdef USE_API
15#endif
16
17#ifdef USE_SERIAL_PROXY_USB_IDENTITY
19#endif
20
21#ifdef USE_SERIAL_PROXY_HOST_UART
23#endif
24
26
27ESPHOME_LOG_TAG(TAG, "serial_proxy");
28
31
33 // Set up modem control pins if configured
34 if (this->rts_pin_ != nullptr) {
35 this->rts_pin_->setup();
36 this->rts_pin_->digital_write(this->rts_state_);
37 }
38 if (this->dtr_pin_ != nullptr) {
39 this->dtr_pin_->setup();
40 this->dtr_pin_->digital_write(this->dtr_state_);
41 }
42#ifdef USE_API
43 // instance_index_ is fixed at registration time; pre-set it so loop() only needs to update data
45#endif
46#ifdef USE_SERIAL_PROXY_USB_IDENTITY
47 if (this->usb_channel_ != nullptr) {
48 this->usb_channel_->get_parent()->add_on_connection_callback(
49 [this](bool connected) { this->on_usb_connection_changed_(connected); });
50 }
51#endif
52#ifdef USE_SERIAL_PROXY_TAP
53 // A tap sets itself up before this runs (its setup priority is higher), so it may
54 // already be waiting on the port -- a boot-time handshake with the device, say. Leaving
55 // the loop enabled is what lets that finish; without it the tap would stall until a
56 // client happened to subscribe.
57 if (this->tap_ != nullptr && this->tap_->tap_needs_port()) {
58 return;
59 }
60#endif
61 // No subscriber at startup; disable loop until a client subscribes
62 this->disable_loop();
63}
64
65#ifdef USE_SERIAL_PROXY_TAP
67 // The mode belongs to a session, not to the port. Carrying a departed client's choice
68 // over to the next one would inject protocol bytes into a stream that never asked for
69 // them -- a firmware upload, or any client built before this request existed and so
70 // unable to turn it off. Guessing RAW is the safe direction: a client that wanted
71 // protocol handling and did not ask for it merely sends its own acknowledgements.
73 return;
74 }
75 ESP_LOGD(TAG, "Session ended, returning serial proxy [%" PRIu32 "] to RAW mode", this->instance_index_);
77}
78#endif
79
81#ifdef USE_API
82 // Detect subscriber disconnect
83 if (this->api_connection_ != nullptr && (this->api_connection_->is_marked_for_removal() ||
84 !this->api_connection_->is_connection_setup() || !api_is_connected())) {
85 ESP_LOGW(TAG, "Subscriber disconnected");
86 this->api_connection_ = nullptr;
87 this->reset_mode_();
88 }
89
90 // With no subscriber there is normally nothing to do, but a tap may still need the port
91 // read -- it does its protocol work precisely while nobody else is listening.
92 if (this->api_connection_ == nullptr) [[unlikely]] {
93#ifdef USE_SERIAL_PROXY_TAP
94 if (this->tap_ == nullptr || !this->tap_->tap_needs_port()) {
95 this->disable_loop();
96 return;
97 }
98#else
99 this->disable_loop();
100 return;
101#endif
102 }
103
104 // Read available data from UART and forward to subscribed client
105 size_t available = this->available();
106 if (available == 0)
107 return;
108
109 this->read_and_send_(available);
110#endif
111}
112
113#ifdef USE_API
114void __attribute__((noinline)) SerialProxy::read_and_send_(size_t available) {
115 // A message the subscriber's connection cannot take is lost, so the bytes stay in the
116 // UART's buffer until it can. A tap is still served: its answers must not wait on the network.
117 if (this->api_connection_ != nullptr &&
118#ifdef USE_SERIAL_PROXY_TAP
119 !this->tap_observing_() &&
120#endif
121 !this->api_connection_->try_to_clear_buffer(false)) {
122 return;
123 }
124
125 // Read in chunks up to SERIAL_PROXY_MAX_READ_SIZE
127 size_t to_read = std::min(available, sizeof(buffer));
128
129 if (!this->read_array(buffer, to_read))
130 return;
131
132#ifdef USE_SERIAL_PROXY_TAP
133 // Before forwarding, so a tap that answers the device (an acknowledgement, say) is not
134 // waiting on the network round trip to a subscriber that may not even exist.
135 if (this->tap_observing_()) {
136 this->tap_->on_device_rx(buffer, to_read);
137 }
138#endif
139
140 if (this->api_connection_ == nullptr) {
141 return;
142 }
143 this->outgoing_msg_.set_data(buffer, to_read);
145}
146#endif
147
148#ifdef USE_SERIAL_PROXY_TAP
149
151 if (this->tap_ == nullptr) {
152 return false;
153 }
154 // With no subscriber, a tap doing its own protocol work (the boot-time handshake with
155 // the device, say) is served regardless of mode -- nobody has chosen one yet. Once a
156 // subscriber holds the port, the mode alone decides, so RAW stays inert.
157 if (this->api_connection_ == nullptr && this->tap_->tap_needs_port()) {
158 return true;
159 }
160 // Otherwise the mode decides. RAW must be inert: a client that flips to RAW before
161 // flashing firmware is entitled to a byte pipe with nothing injecting protocol bytes
162 // into it, and "the tap turned out not to recognise the stream" is not good enough.
164}
165
167#ifdef USE_API
168 // Nothing would consume the bytes; leave them in the FIFO
169 if (!this->tap_observing_() && this->api_connection_ == nullptr) {
170 return;
171 }
172 const size_t available = this->available();
173 if (available > 0) {
174 this->read_and_send_(available);
175 }
176#endif
177}
178#endif
179
181 ESP_LOGCONFIG(TAG,
182 "Serial Proxy [%" PRIu32 "]:\n"
183 " Name: %s\n"
184 " Port Type: %s\n"
185 " RTS Pin: %s\n"
186 " DTR Pin: %s",
187 this->instance_index_, this->name_ != nullptr ? this->name_ : "",
188 this->port_type_ == api::enums::SERIAL_PROXY_PORT_TYPE_RS485 ? LOG_STR_LITERAL("RS485")
189 : this->port_type_ == api::enums::SERIAL_PROXY_PORT_TYPE_RS232 ? LOG_STR_LITERAL("RS232")
190 : this->port_type_ == api::enums::SERIAL_PROXY_PORT_TYPE_USB_SERIAL ? LOG_STR_LITERAL("USB_SERIAL")
191 : LOG_STR_LITERAL("TTL"),
192 this->rts_pin_ != nullptr ? LOG_STR_LITERAL("configured") : LOG_STR_LITERAL("not configured"),
193 this->dtr_pin_ != nullptr ? LOG_STR_LITERAL("configured") : LOG_STR_LITERAL("not configured"));
194}
195
196SerialProxyResult SerialProxy::configure(api::APIConnection *api_connection, uint32_t baudrate, bool flow_control,
197 uint8_t parity, uint8_t stop_bits, uint8_t data_size) {
198#ifdef USE_API
199 if (!this->is_subscriber_(api_connection)) {
200 ESP_LOGW(TAG, "Ignoring configure request from client without port subscription [%" PRIu32 "]",
201 this->instance_index_);
203 }
204#endif
205 ESP_LOGD(TAG,
206 "Configuring serial proxy [%" PRIu32 "]: baud=%" PRIu32 ", flow_ctrl=%s, parity=%" PRIu8 ", stop=%" PRIu8
207 ", data=%" PRIu8,
208 this->instance_index_, baudrate, YESNO(flow_control), parity, stop_bits, data_size);
209
210 auto *uart_comp = this->parent_;
211 if (uart_comp == nullptr) {
212 ESP_LOGE(TAG, "UART component not available");
214 }
215
216 // Validate all parameters before applying any (values come from a remote client)
217 if (baudrate == 0) {
218 ESP_LOGW(TAG, "Invalid baud rate: 0");
220 }
222 ESP_LOGW(TAG, "Invalid stop bits: %u (must be 1 or 2)", stop_bits);
224 }
225 if (data_size < 5 || data_size > 8) {
226 ESP_LOGW(TAG, "Invalid data bits: %u (must be 5-8)", data_size);
228 }
229 if (parity > 2) {
230 ESP_LOGW(TAG, "Invalid parity: %u (must be 0-2)", parity);
232 }
233 // The API carries only RTS/CTS, as CRTSCTS does
234 const uart::UARTFlowControl uart_flow_control =
236
237 // Skip a no-op reconfigure. Clients routinely re-send identical settings on every
238 // port open, and on a USB UART each apply is a CDC SET_LINE_CODING control transfer.
239 // Some bridges watch line-coding changes as a signalling channel (a magic baud
240 // sequence to enter a bootloader, say), so redundant applies are not harmless.
241 static const uart::UARTParityOptions PARITY_MAP[] = {
245 };
246 if (uart_comp->get_baud_rate() == baudrate && uart_comp->get_stop_bits() == stop_bits &&
247 uart_comp->get_data_bits() == data_size && uart_comp->get_parity() == PARITY_MAP[parity] &&
248 uart_comp->get_flow_control() == uart_flow_control) {
249 ESP_LOGV(TAG, "Settings unchanged, skipping reconfigure [%" PRIu32 "]", this->instance_index_);
251 }
252
253 // Apply validated parameters
254 uart_comp->set_baud_rate(baudrate);
255 uart_comp->set_stop_bits(stop_bits);
256 uart_comp->set_data_bits(data_size);
257
258 uart_comp->set_parity(PARITY_MAP[parity]);
259 uart_comp->set_flow_control(uart_flow_control);
260
261 // load_settings() is available on ESP8266 and ESP32 platforms
262#if defined(USE_ESP8266) || defined(USE_ESP32)
263 uart_comp->load_settings(true);
264#endif
266}
267
270#ifdef USE_API
271 // Only the live subscriber may change the mode, so the mode cannot outlive a session
272 if (!this->is_subscriber_(api_connection)) {
273 ESP_LOGW(TAG, "Ignoring mode request from client without port subscription [%" PRIu32 "]", this->instance_index_);
275 }
276#endif
277 // Values come from a remote client
279 ESP_LOGW(TAG, "Invalid mode: %" PRIu32, static_cast<uint32_t>(mode));
281 }
282 // PROTOCOL on a port with no tap would be a silent no-op; refuse so the client knows
283#ifdef USE_SERIAL_PROXY_TAP
284 const bool has_tap = this->tap_ != nullptr;
285#else
286 const bool has_tap = false;
287#endif
288 if (mode == api::enums::SERIAL_PROXY_MODE_PROTOCOL && !has_tap) {
289 ESP_LOGW(TAG, "No tap on serial proxy [%" PRIu32 "]; PROTOCOL mode unavailable", this->instance_index_);
291 }
292 ESP_LOGD(TAG, "Serial proxy [%" PRIu32 "] mode set to %s", this->instance_index_,
293 mode == api::enums::SERIAL_PROXY_MODE_PROTOCOL ? LOG_STR_LITERAL("PROTOCOL") : LOG_STR_LITERAL("RAW"));
294#ifdef USE_SERIAL_PROXY_TAP
295 const bool entering_protocol_mode =
297 const bool leaving_protocol_mode =
299 this->mode_ = mode;
300
301 if (entering_protocol_mode && this->tap_ != nullptr) {
302 this->tap_->on_protocol_enabled();
303 }
304
305 // Only for an explicit client request, not for reset_mode_() at the end of a session:
306 // an ordinary disconnect says nothing about the device, whereas a client deliberately
307 // asking for raw bytes usually precedes changing what the device is.
308 if (leaving_protocol_mode && this->tap_ != nullptr) {
309 this->tap_->on_protocol_disabled();
310 }
311#endif
313}
314
315void SerialProxy::write_from_client(api::APIConnection *api_connection, const uint8_t *data, size_t len) {
316#ifdef USE_API
317 // Bytes from anyone but the live subscriber would interleave with the subscriber's
318 // traffic -- or with an active tap's -- on the wire
319 if (!this->is_subscriber_(api_connection)) {
320 if (this->api_connection_ != nullptr) {
321 ESP_LOGW(TAG, "Ignoring write from client that does not hold serial proxy [%" PRIu32 "]", this->instance_index_);
322 } else {
323 // A legacy client streaming writes without subscribing would flood WARN, one per
324 // request; writes are the only high-rate, unacknowledged operation, so keep this
325 // visible without drowning the log
326 ESP_LOGV(TAG, "Ignoring write from client without port subscription [%" PRIu32 "]", this->instance_index_);
327 }
328 return;
329 }
330#endif
331 if (data == nullptr || len == 0)
332 return;
333 // Whatever the driver cannot buffer stalls the main loop for its wire time. At high baud
334 // rates that is brief and losing nothing is worth it; at low ones it would trip the
335 // watchdog, so cap the stall and drop the rest. The cap covers the whole loop pass:
336 // several writes can arrive in one, and each alone might stay under it.
337 const size_t free = this->parent_->available_for_write();
338 bool trimmed = false;
339 if (len > free) {
340 const uint32_t loop_time = App.get_loop_component_start_time();
341 if (loop_time != stall_loop_time) {
342 stall_loop_time = loop_time;
343 stall_spent_ms = 0;
344 }
345 const uint32_t stall_ms = this->wire_time_ms_(len - free);
346 trimmed = stall_spent_ms + stall_ms > SERIAL_PROXY_MAX_WRITE_STALL_MS;
347 if (trimmed && !this->trim_warned_) {
348 ESP_LOGW(TAG,
349 "TX buffer full on serial proxy [%" PRIu32 "]: dropping %zu of %zu bytes (would stall %" PRIu32
350 " ms at %" PRIu32 " baud); raise the UART tx_buffer_size or pace writes",
351 this->instance_index_, len - free, len, stall_ms, this->parent_->get_baud_rate());
352 }
353 if (trimmed) {
354 len = free;
355 } else {
356 stall_spent_ms += stall_ms;
357 }
358 }
359 this->trim_warned_ = trimmed;
360 if (len == 0)
361 return;
362 this->write_array(data, len);
363
364#ifdef USE_SERIAL_PROXY_TAP
365 // After the write, so the tap observes the same ordering the device does
366 if (this->tap_observing_()) {
367 this->tap_->on_client_tx(data, len);
368 }
369#endif
370}
371
373 const uint32_t bits_per_byte = 1 + this->parent_->get_data_bits() + this->parent_->get_stop_bits() +
375 return static_cast<uint64_t>(bytes) * bits_per_byte * 1000 / std::max<uint32_t>(this->parent_->get_baud_rate(), 1);
376}
377
379#ifdef USE_API
380 if (!this->is_subscriber_(api_connection)) {
381 ESP_LOGW(TAG, "Ignoring modem pin request from client without port subscription [%" PRIu32 "]",
382 this->instance_index_);
384 }
385#endif
386 // Asserting a pin that is not configured must fail so the client learns the signal never
387 // reached the wire; deasserting an absent pin is harmless and stays allowed. Clients can
388 // avoid this by masking against SerialProxyInfo.configured_line_states.
389 if ((line_states & ~this->get_configured_modem_pins()) != 0) {
390 ESP_LOGW(TAG, "Requested modem pin not configured on serial proxy [%" PRIu32 "]", this->instance_index_);
392 }
393 const bool rts = (line_states & SERIAL_PROXY_LINE_STATE_FLAG_RTS) != 0;
394 const bool dtr = (line_states & SERIAL_PROXY_LINE_STATE_FLAG_DTR) != 0;
395 ESP_LOGV(TAG, "Setting modem pins [%" PRIu32 "]: RTS=%s, DTR=%s", this->instance_index_, ONOFF(rts), ONOFF(dtr));
396
397 // The UART goes first, so a failure leaves every line as it was. A line with a GPIO pin keeps
398 // the UART's current state; with both on GPIO there is nothing to send
399 bool applied = true;
400 if (this->rts_pin_ == nullptr || this->dtr_pin_ == nullptr) {
401 this->with_modem_uart_([this, dtr, rts, &applied](auto *uart) {
402 applied = uart->set_modem_control(this->dtr_pin_ != nullptr ? uart->get_dtr() : dtr,
403 this->rts_pin_ != nullptr ? uart->get_rts() : rts);
404 });
405 }
406 if (!applied) {
407 ESP_LOGW(TAG, "Modem pins did not reach the UART on serial proxy [%" PRIu32 "]", this->instance_index_);
409 }
410 if (this->rts_pin_ != nullptr) {
411 this->rts_state_ = rts;
412 this->rts_pin_->digital_write(rts);
413 }
414 if (this->dtr_pin_ != nullptr) {
415 this->dtr_state_ = dtr;
416 this->dtr_pin_->digital_write(dtr);
417 }
419}
420
421#ifdef USE_API
425 this->fill_identity_(scratch, msg);
426 api_connection->send_serial_proxy_identity(msg);
427}
428
430 msg.instance = this->instance_index_;
431#ifdef USE_SERIAL_PROXY_USB_IDENTITY
432 // The define is global, so a hardware UART port in the same config also gets here
433 if (this->usb_channel_ != nullptr) {
435 // Covers a removed device, a channel the device has no CDC function for and a failed channel setup
436 if (!this->usb_channel_->is_connected()) {
437 return;
438 }
439 auto *client = this->usb_channel_->get_parent();
441 if (!client->get_device_info(scratch)) {
443 return;
444 }
445 msg.usb.vendor_id = scratch.vendor_id;
446 msg.usb.product_id = scratch.product_id;
447 msg.usb.bcd_device = scratch.bcd_device;
451 msg.manufacturer = StringRef(scratch.manufacturer);
452 msg.product = StringRef(scratch.product);
453 msg.serial_number = StringRef(scratch.serial_number);
454 return;
455 }
456#endif
457 // Zero-initialized message: source NONE, no flags
458}
459#endif
460
461#ifdef USE_SERIAL_PROXY_USB_IDENTITY
463 ESP_LOGD(TAG, "USB device %s serial proxy [%" PRIu32 "]",
464 connected ? LOG_STR_LITERAL("attached to") : LOG_STR_LITERAL("removed from"), this->instance_index_);
465#ifdef USE_SERIAL_PROXY_TAP
466 // Before telling clients, so a tap never acknowledges a frame from the old device after
467 // a client has been told it is gone. The subscriber and the mode stay: both belong to
468 // the client's session, and only the client knows whether that session is over.
469 if (!connected && this->tap_ != nullptr) {
471 }
472#endif
473#ifdef USE_API
474 if (api::global_api_server == nullptr) {
475 return;
476 }
479 this->fill_identity_(scratch, msg);
481#endif
482}
483#endif
484
486 bool rts = this->rts_state_;
487 bool dtr = this->dtr_state_;
488 this->with_modem_uart_([this, &rts, &dtr](auto *uart) {
489 if (this->rts_pin_ == nullptr)
490 rts = uart->get_rts();
491 if (this->dtr_pin_ == nullptr)
492 dtr = uart->get_dtr();
493 });
494 return (rts ? static_cast<uint32_t>(SERIAL_PROXY_LINE_STATE_FLAG_RTS) : 0u) |
495 (dtr ? static_cast<uint32_t>(SERIAL_PROXY_LINE_STATE_FLAG_DTR) : 0u);
496}
497
499#ifdef USE_API
500 // Flushing stalls the port, so it gets the same ownership check as writes
501 if (!this->is_subscriber_(api_connection)) {
502 ESP_LOGW(TAG, "Ignoring flush from client without port subscription [%" PRIu32 "]", this->instance_index_);
504 }
505#endif
506 ESP_LOGV(TAG, "Flushing serial proxy [%" PRIu32 "]", this->instance_index_);
507 switch (this->flush()) {
516 }
517 return SerialProxyResult::SERIAL_PROXY_RESULT_ERROR; // Unreachable; all enum values handled above
518}
519
520#ifdef USE_API
523 switch (type) {
525 if (this->api_connection_ == api_connection) {
526 ESP_LOGV(TAG, "API connection is already subscribed to serial proxy [%" PRIu32 "]", this->instance_index_);
528 }
529 if (this->api_connection_ != nullptr) {
530 // A living subscriber keeps exclusive access. Its connection may be dead without
531 // loop() having noticed yet (e.g. the client crashed and reconnected quickly);
532 // in that case let the new client take over instead of locking it out.
534 ESP_LOGE(TAG, "Only one API subscription is allowed at a time");
536 }
537 ESP_LOGW(TAG, "Previous subscriber disconnected; taking over subscription");
538 // End the dead client's session before starting the new one, so its mode
539 // cannot leak into a session that never asked for it
540 this->api_connection_ = nullptr;
541 this->reset_mode_();
542 }
543 this->api_connection_ = api_connection;
544 this->enable_loop();
545 ESP_LOGV(TAG, "API connection subscribed to serial proxy [%" PRIu32 "]", this->instance_index_);
548 // Unsubscribe is idempotent: not being subscribed is not an error
549 if (this->api_connection_ != api_connection) {
550 ESP_LOGV(TAG, "API connection is not subscribed to serial proxy [%" PRIu32 "]", this->instance_index_);
552 }
553 this->api_connection_ = nullptr;
554 this->reset_mode_();
555#ifdef USE_SERIAL_PROXY_TAP
556 // Keep the loop alive for a tap that still needs the port (mirrors loop())
557 if (this->tap_ == nullptr || !this->tap_->tap_needs_port()) {
558 this->disable_loop();
559 }
560#else
561 this->disable_loop();
562#endif
563 ESP_LOGV(TAG, "API connection unsubscribed from serial proxy [%" PRIu32 "]", this->instance_index_);
565 default:
566 ESP_LOGW(TAG, "Unknown serial proxy request type: %" PRIu32, static_cast<uint32_t>(type));
568 }
569}
570#endif
571
572} // namespace esphome::serial_proxy
573
574#endif // USE_SERIAL_PROXY
BedjetMode mode
BedJet operating mode.
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.
void enable_loop()
Enable this component's loop.
Definition component.h:261
void disable_loop()
Disable this component's loop.
virtual void setup()=0
virtual void digital_write(bool value)=0
T * get_parent() const
Get the parent of this object.
Definition helpers.h:2166
StringRef is a reference to a string owned by something else.
Definition string_ref.h:31
void send_serial_proxy_data(const SerialProxyDataReceived &msg)
void send_serial_proxy_identity(const SerialProxyIdentity &msg)
Send a port identity to this client.
bool try_to_clear_buffer(bool log_out_of_space)
void send_serial_proxy_identity(const SerialProxyIdentity &msg)
Tell every subscribed client that a serial proxy port's identity changed.
void set_data(const uint8_t *data, size_t len)
Definition api_pb2.h:3941
enums::SerialProxyIdentitySource source
Definition api_pb2.h:4125
void fill_identity_(IdentityScratch &scratch, api::SerialProxyIdentity &msg) const
Fill an identity message for this port.
SerialProxyResult 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.
void read_and_send_(size_t available)
Read from UART, hand the bytes to any tap, and forward them to a subscriber (slow path with a 256-byt...
api::enums::SerialProxyMode mode_
How the bytes passing through are treated; zero is SERIAL_PROXY_MODE_RAW.
SerialProxyResult serial_proxy_request(api::APIConnection *api_connection, api::enums::SerialProxyRequestType type)
Handle a subscribe/unsubscribe request from an API client.
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 trim_warned_
Set while writes are being trimmed, so a client streaming into a slow port warns once.
bool rts_state_
Current modem pin states.
SerialProxyResult flush_port(api::APIConnection *api_connection)
Flush the serial port (block until all TX data is sent)
uint32_t get_configured_modem_pins() const
Get the modem pins this instance can drive as a bitmask of SerialProxyLineStateFlag values.
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.
usb_uart::USBUartChannel * usb_channel_
The USB UART channel behind this port; nullptr on non-USB ports.
void on_usb_connection_changed_(bool connected)
The USB device behind this port was attached or removed; report the port's new identity to every subs...
bool tap_observing_() const
True when the tap should be shown the traffic passing through this port.
SerialProxyResult set_modem_pins(api::APIConnection *api_connection, uint32_t line_states)
Set modem pin states from a bitmask of SerialProxyLineStateFlag values.
SerialProxyResult set_mode_from_client(api::APIConnection *api_connection, api::enums::SerialProxyMode mode)
Handle a mode change requested by an API client.
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.
static uint32_t stall_loop_time
Stall spent by writes in the current loop pass, keyed by the pass's cached start time.
bool is_subscriber_(api::APIConnection *api_connection) const
True when the given connection is the live subscriber.
void tap_pump()
Run one read-and-dispatch cycle immediately.
void send_identity(api::APIConnection *api_connection)
Send this port's identity to one client.
void reset_mode_()
Return the port to RAW when a subscriber goes away, so the mode never outlives it.
api::APIConnection * api_connection_
Subscribed API client (only one allowed at a time)
uint32_t wire_time_ms_(size_t bytes) const
Time the wire needs for the given number of bytes at the current framing.
bool with_modem_uart_(F &&f) const
Call f with the UART behind this port if that UART drives the modem lines itself.
virtual void on_device_disconnected()=0
The device behind the port went away – unplugged, or its power was cut.
virtual void on_protocol_enabled()=0
A client turned protocol handling on for this port.
virtual bool tap_needs_port() const =0
True when the port must keep reading even with no subscriber attached, so a tap can do its own protoc...
virtual void on_device_rx(const uint8_t *data, size_t len)=0
Bytes read from the device, before they are forwarded to any subscriber.
virtual void on_client_tx(const uint8_t *data, size_t len)=0
Bytes a subscriber sent towards the device, after they have been written.
virtual void on_protocol_disabled()=0
A client explicitly turned protocol handling off for this port.
UARTParityOptions get_parity() const
void set_baud_rate(uint32_t baud_rate)
virtual size_t available_for_write()
UARTFlushResult flush()
Definition uart.h:96
optional< std::array< uint8_t, N > > read_array()
Definition uart.h:43
UARTComponent * parent_
Definition uart.h:134
void write_array(const uint8_t *data, size_t len)
Definition uart.h:30
uint8_t UARTParityOptions parity
Definition uart.h:119
uint8_t get_interface_class() const
bInterfaceClass of the interface get_interface_number() names
Definition usb_uart.h:180
uint8_t get_port_number() const
Index of this port among the ports on its interface.
Definition usb_uart.h:187
uint8_t get_interface_number() const
USB interface number a host driver binds to for this channel: the communication interface of a CDC AC...
Definition usb_uart.h:174
struct @66::@67 __attribute__
Wake the main loop task from an ISR. ISR-safe.
Definition main_task.h:45
uint8_t type
uint32_t buffer
Definition gif.cpp:50
@ SERIAL_PROXY_PORT_TYPE_RS232
Definition api_pb2.h:28
@ SERIAL_PROXY_PORT_TYPE_RS485
Definition api_pb2.h:29
@ SERIAL_PROXY_PORT_TYPE_USB_SERIAL
Definition api_pb2.h:30
@ SERIAL_PROXY_REQUEST_TYPE_UNSUBSCRIBE
Definition api_pb2.h:360
@ SERIAL_PROXY_REQUEST_TYPE_SUBSCRIBE
Definition api_pb2.h:359
@ SERIAL_PROXY_IDENTITY_FLAG_CONNECTED
Definition api_pb2.h:387
@ SERIAL_PROXY_IDENTITY_FLAG_ERROR
Definition api_pb2.h:388
@ SERIAL_PROXY_IDENTITY_SOURCE_USB
Definition api_pb2.h:382
APIServer * global_api_server
@ SERIAL_PROXY_LINE_STATE_FLAG_RTS
RTS (Request To Send)
@ SERIAL_PROXY_LINE_STATE_FLAG_DTR
DTR (Data Terminal Ready)
SerialProxyResult
Result of a client-initiated operation; mapped to api::enums::SerialProxyStatus by the API layer.
@ SERIAL_PROXY_RESULT_TIMEOUT
Timed out before TX completed.
@ SERIAL_PROXY_RESULT_ERROR
Driver or hardware error.
@ SERIAL_PROXY_RESULT_NOT_SUPPORTED
Requested feature is not available on this instance.
@ SERIAL_PROXY_RESULT_PORT_IN_USE
Denied: another live client holds the port.
@ SERIAL_PROXY_RESULT_OK
Operation completed or request accepted.
@ SERIAL_PROXY_RESULT_INVALID_ARGUMENT
A parameter value is out of range.
@ SERIAL_PROXY_RESULT_ASSUMED_SUCCESS
Platform cannot confirm TX drain; success assumed.
constexpr size_t SERIAL_PROXY_MAX_READ_SIZE
Maximum bytes to read from UART in a single loop iteration.
constexpr uint32_t SERIAL_PROXY_MAX_WRITE_STALL_MS
Longest main-loop stall client writes may cause per loop pass, shared by every instance; bytes the UA...
ESPHOME_LOG_TAG(TAG, "serial_proxy")
@ UART_FLUSH_RESULT_ASSUMED_SUCCESS
Platform cannot report result; success is assumed.
@ UART_FLUSH_RESULT_SUCCESS
Confirmed: all bytes left the TX FIFO.
@ UART_FLUSH_RESULT_FAILED
Confirmed: driver or hardware error.
@ UART_FLUSH_RESULT_TIMEOUT
Confirmed: timed out before TX completed.
const void size_t len
Definition hal.h:68
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
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
watchdog_hw scratch[0]