ESPHome 2026.12.0-dev
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
36#ifdef USE_API
37 // instance_index_ is fixed at registration time; pre-set it so loop() only needs to update data
39#endif
40#ifdef USE_SERIAL_PROXY_USB_IDENTITY
41 if (this->usb_channel_ != nullptr) {
42 this->usb_channel_->get_parent()->add_on_connection_callback(
43 [this](bool connected) { this->on_usb_connection_changed_(connected); });
44 }
45#endif
46#ifdef USE_SERIAL_PROXY_TAP
47 // A tap sets itself up before this runs (its setup priority is higher), so it may
48 // already be waiting on the port -- a boot-time handshake with the device, say. Leaving
49 // the loop enabled is what lets that finish; without it the tap would stall until a
50 // client happened to subscribe.
51 if (this->tap_ != nullptr && this->tap_->tap_needs_port()) {
52 return;
53 }
54#endif
55 // No subscriber at startup; disable loop until a client subscribes
56 this->disable_loop();
57}
58
59#ifdef USE_SERIAL_PROXY_TAP
61 // The mode belongs to a session, not to the port. Carrying a departed client's choice
62 // over to the next one would inject protocol bytes into a stream that never asked for
63 // them -- a firmware upload, or any client built before this request existed and so
64 // unable to turn it off. Guessing RAW is the safe direction: a client that wanted
65 // protocol handling and did not ask for it merely sends its own acknowledgements.
67 return;
68 }
69 ESP_LOGD(TAG, "Session ended, returning serial proxy [%" PRIu32 "] to RAW mode", this->instance_index_);
71}
72#endif
73
75#ifdef USE_API
76 // Detect subscriber disconnect
77 if (this->api_connection_ != nullptr && (this->api_connection_->is_marked_for_removal() ||
78 !this->api_connection_->is_authenticated() || !api_is_connected())) {
79 ESP_LOGW(TAG, "Subscriber disconnected");
80 this->api_connection_ = nullptr;
81 this->reset_mode_();
82 }
83
84 // With no subscriber there is normally nothing to do, but a tap may still need the port
85 // read -- it does its protocol work precisely while nobody else is listening.
86 if (this->api_connection_ == nullptr) [[unlikely]] {
87#ifdef USE_SERIAL_PROXY_TAP
88 if (this->tap_ == nullptr || !this->tap_->tap_needs_port()) {
89 this->disable_loop();
90 return;
91 }
92#else
93 this->disable_loop();
94 return;
95#endif
96 }
97
98 // Read available data from UART and forward to subscribed client
99 size_t available = this->available();
100 if (available == 0)
101 return;
102
103 this->read_and_send_(available);
104#endif
105}
106
107#ifdef USE_API
108void __attribute__((noinline)) SerialProxy::read_and_send_(size_t available) {
109 // A message the subscriber's connection cannot take is lost, so the bytes stay in the
110 // UART's buffer until it can. A tap is still served: its answers must not wait on the network.
111 if (this->api_connection_ != nullptr &&
112#ifdef USE_SERIAL_PROXY_TAP
113 !this->tap_observing_() &&
114#endif
115 !this->api_connection_->try_to_clear_buffer(false)) {
116 return;
117 }
118
119 // Read in chunks up to SERIAL_PROXY_MAX_READ_SIZE
121 size_t to_read = std::min(available, sizeof(buffer));
122
123 if (!this->read_array(buffer, to_read))
124 return;
125
126#ifdef USE_SERIAL_PROXY_TAP
127 // Before forwarding, so a tap that answers the device (an acknowledgement, say) is not
128 // waiting on the network round trip to a subscriber that may not even exist.
129 if (this->tap_observing_()) {
130 this->tap_->on_device_rx(buffer, to_read);
131 }
132#endif
133
134 if (this->api_connection_ == nullptr) {
135 return;
136 }
137 this->outgoing_msg_.set_data(buffer, to_read);
139}
140#endif
141
142#ifdef USE_SERIAL_PROXY_TAP
143
145 if (this->tap_ == nullptr) {
146 return false;
147 }
148 // With no subscriber, a tap doing its own protocol work (the boot-time handshake with
149 // the device, say) is served regardless of mode -- nobody has chosen one yet. Once a
150 // subscriber holds the port, the mode alone decides, so RAW stays inert.
151 if (this->api_connection_ == nullptr && this->tap_->tap_needs_port()) {
152 return true;
153 }
154 // Otherwise the mode decides. RAW must be inert: a client that flips to RAW before
155 // flashing firmware is entitled to a byte pipe with nothing injecting protocol bytes
156 // into it, and "the tap turned out not to recognise the stream" is not good enough.
158}
159
161#ifdef USE_API
162 // Nothing would consume the bytes; leave them in the FIFO
163 if (!this->tap_observing_() && this->api_connection_ == nullptr) {
164 return;
165 }
166 const size_t available = this->available();
167 if (available > 0) {
168 this->read_and_send_(available);
169 }
170#endif
171}
172#endif
173
175 ESP_LOGCONFIG(TAG,
176 "Serial Proxy [%" PRIu32 "]:\n"
177 " Name: %s\n"
178 " Port Type: %s\n"
179 " RTS Pin: %s\n"
180 " DTR Pin: %s",
181 this->instance_index_, this->name_ != nullptr ? this->name_ : "",
182 this->port_type_ == api::enums::SERIAL_PROXY_PORT_TYPE_RS485 ? LOG_STR_LITERAL("RS485")
183 : this->port_type_ == api::enums::SERIAL_PROXY_PORT_TYPE_RS232 ? LOG_STR_LITERAL("RS232")
184 : this->port_type_ == api::enums::SERIAL_PROXY_PORT_TYPE_USB_SERIAL ? LOG_STR_LITERAL("USB_SERIAL")
185 : LOG_STR_LITERAL("TTL"),
186 this->rts_pin_ != nullptr ? LOG_STR_LITERAL("configured") : LOG_STR_LITERAL("not configured"),
187 this->dtr_pin_ != nullptr ? LOG_STR_LITERAL("configured") : LOG_STR_LITERAL("not configured"));
188}
189
190SerialProxyResult SerialProxy::configure(api::APIConnection *api_connection, uint32_t baudrate, bool flow_control,
191 uint8_t parity, uint8_t stop_bits, uint8_t data_size) {
192#ifdef USE_API
193 if (!this->is_subscriber_(api_connection)) {
194 ESP_LOGW(TAG, "Ignoring configure request from client without port subscription [%" PRIu32 "]",
195 this->instance_index_);
197 }
198#endif
199 ESP_LOGD(TAG,
200 "Configuring serial proxy [%" PRIu32 "]: baud=%" PRIu32 ", flow_ctrl=%s, parity=%" PRIu8 ", stop=%" PRIu8
201 ", data=%" PRIu8,
202 this->instance_index_, baudrate, YESNO(flow_control), parity, stop_bits, data_size);
203
204 auto *uart_comp = this->parent_;
205 if (uart_comp == nullptr) {
206 ESP_LOGE(TAG, "UART component not available");
208 }
209
210 // Validate all parameters before applying any (values come from a remote client)
211 if (baudrate == 0) {
212 ESP_LOGW(TAG, "Invalid baud rate: 0");
214 }
216 ESP_LOGW(TAG, "Invalid stop bits: %u (must be 1 or 2)", stop_bits);
218 }
219 if (data_size < 5 || data_size > 8) {
220 ESP_LOGW(TAG, "Invalid data bits: %u (must be 5-8)", data_size);
222 }
223 if (parity > 2) {
224 ESP_LOGW(TAG, "Invalid parity: %u (must be 0-2)", parity);
226 }
227 // The API carries only RTS/CTS, as CRTSCTS does
228 const uart::UARTFlowControl uart_flow_control =
230
231 // Skip a no-op reconfigure. Clients routinely re-send identical settings on every
232 // port open, and on a USB UART each apply is a CDC SET_LINE_CODING control transfer.
233 // Some bridges watch line-coding changes as a signalling channel (a magic baud
234 // sequence to enter a bootloader, say), so redundant applies are not harmless.
235 static const uart::UARTParityOptions PARITY_MAP[] = {
239 };
240 if (uart_comp->get_baud_rate() == baudrate && uart_comp->get_stop_bits() == stop_bits &&
241 uart_comp->get_data_bits() == data_size && uart_comp->get_parity() == PARITY_MAP[parity] &&
242 uart_comp->get_flow_control() == uart_flow_control) {
243 ESP_LOGV(TAG, "Settings unchanged, skipping reconfigure [%" PRIu32 "]", this->instance_index_);
245 }
246
247 // Apply validated parameters
248 uart_comp->set_baud_rate(baudrate);
249 uart_comp->set_stop_bits(stop_bits);
250 uart_comp->set_data_bits(data_size);
251
252 uart_comp->set_parity(PARITY_MAP[parity]);
253 uart_comp->set_flow_control(uart_flow_control);
254
255#ifdef USE_UART_LOAD_SETTINGS
256 uart_comp->load_settings(true);
257#endif
259}
260
263#ifdef USE_API
264 // Only the live subscriber may change the mode, so the mode cannot outlive a session
265 if (!this->is_subscriber_(api_connection)) {
266 ESP_LOGW(TAG, "Ignoring mode request from client without port subscription [%" PRIu32 "]", this->instance_index_);
268 }
269#endif
270 // Values come from a remote client
272 ESP_LOGW(TAG, "Invalid mode: %" PRIu32, static_cast<uint32_t>(mode));
274 }
275 // PROTOCOL on a port with no tap would be a silent no-op; refuse so the client knows
276#ifdef USE_SERIAL_PROXY_TAP
277 const bool has_tap = this->tap_ != nullptr;
278#else
279 const bool has_tap = false;
280#endif
281 if (mode == api::enums::SERIAL_PROXY_MODE_PROTOCOL && !has_tap) {
282 ESP_LOGW(TAG, "No tap on serial proxy [%" PRIu32 "]; PROTOCOL mode unavailable", this->instance_index_);
284 }
285 ESP_LOGD(TAG, "Serial proxy [%" PRIu32 "] mode set to %s", this->instance_index_,
286 mode == api::enums::SERIAL_PROXY_MODE_PROTOCOL ? LOG_STR_LITERAL("PROTOCOL") : LOG_STR_LITERAL("RAW"));
287#ifdef USE_SERIAL_PROXY_TAP
288 const bool entering_protocol_mode =
290 const bool leaving_protocol_mode =
292 this->mode_ = mode;
293
294 if (entering_protocol_mode && this->tap_ != nullptr) {
295 this->tap_->on_protocol_enabled();
296 }
297
298 // Only for an explicit client request, not for reset_mode_() at the end of a session:
299 // an ordinary disconnect says nothing about the device, whereas a client deliberately
300 // asking for raw bytes usually precedes changing what the device is.
301 if (leaving_protocol_mode && this->tap_ != nullptr) {
302 this->tap_->on_protocol_disabled();
303 }
304#endif
306}
307
308void SerialProxy::write_from_client(api::APIConnection *api_connection, const uint8_t *data, size_t len) {
309#ifdef USE_API
310 // Bytes from anyone but the live subscriber would interleave with the subscriber's
311 // traffic -- or with an active tap's -- on the wire
312 if (!this->is_subscriber_(api_connection)) {
313 if (this->api_connection_ != nullptr) {
314 ESP_LOGW(TAG, "Ignoring write from client that does not hold serial proxy [%" PRIu32 "]", this->instance_index_);
315 } else {
316 // A legacy client streaming writes without subscribing would flood WARN, one per
317 // request; writes are the only high-rate, unacknowledged operation, so keep this
318 // visible without drowning the log
319 ESP_LOGV(TAG, "Ignoring write from client without port subscription [%" PRIu32 "]", this->instance_index_);
320 }
321 return;
322 }
323#endif
324 if (data == nullptr || len == 0)
325 return;
326 // Whatever the driver cannot buffer stalls the main loop for its wire time. At high baud
327 // rates that is brief and losing nothing is worth it; at low ones it would trip the
328 // watchdog, so cap the stall and drop the rest. The cap covers the whole loop pass:
329 // several writes can arrive in one, and each alone might stay under it.
330 const size_t free = this->parent_->available_for_write();
331 bool trimmed = false;
332 if (len > free) {
333 const uint32_t loop_time = App.get_loop_component_start_time();
334 if (loop_time != stall_loop_time) {
335 stall_loop_time = loop_time;
336 stall_spent_ms = 0;
337 }
338 const uint32_t stall_ms = this->wire_time_ms_(len - free);
339 trimmed = stall_spent_ms + stall_ms > SERIAL_PROXY_MAX_WRITE_STALL_MS;
340 if (trimmed && !this->trim_warned_) {
341 ESP_LOGW(TAG,
342 "TX buffer full on serial proxy [%" PRIu32 "]: dropping %zu of %zu bytes (would stall %" PRIu32
343 " ms at %" PRIu32 " baud); raise the UART tx_buffer_size or pace writes",
344 this->instance_index_, len - free, len, stall_ms, this->parent_->get_baud_rate());
345 }
346 if (trimmed) {
347 len = free;
348 } else {
349 stall_spent_ms += stall_ms;
350 }
351 }
352 this->trim_warned_ = trimmed;
353 if (len == 0)
354 return;
355 this->write_array(data, len);
356
357#ifdef USE_SERIAL_PROXY_TAP
358 // After the write, so the tap observes the same ordering the device does
359 if (this->tap_observing_()) {
360 this->tap_->on_client_tx(data, len);
361 }
362#endif
363}
364
366 const uint32_t bits_per_byte = 1 + this->parent_->get_data_bits() + this->parent_->get_stop_bits() +
368 return static_cast<uint64_t>(bytes) * bits_per_byte * 1000 / std::max<uint32_t>(this->parent_->get_baud_rate(), 1);
369}
370
372#ifdef USE_API
373 if (!this->is_subscriber_(api_connection)) {
374 ESP_LOGW(TAG, "Ignoring modem pin request from client without port subscription [%" PRIu32 "]",
375 this->instance_index_);
377 }
378#endif
379 // Asserting a pin that is not configured must fail so the client learns the signal never
380 // reached the wire; deasserting an absent pin is harmless and stays allowed. Clients can
381 // avoid this by masking against SerialProxyInfo.configured_line_states.
382 if ((line_states & ~this->get_configured_modem_pins()) != 0) {
383 ESP_LOGW(TAG, "Requested modem pin not configured on serial proxy [%" PRIu32 "]", this->instance_index_);
385 }
386 const bool rts = (line_states & SERIAL_PROXY_LINE_STATE_FLAG_RTS) != 0;
387 const bool dtr = (line_states & SERIAL_PROXY_LINE_STATE_FLAG_DTR) != 0;
388 ESP_LOGV(TAG, "Setting modem pins [%" PRIu32 "]: RTS=%s, DTR=%s", this->instance_index_, ONOFF(rts), ONOFF(dtr));
389
390 // The UART goes first, so a failure leaves every line as it was. A line with a GPIO pin keeps
391 // the UART's current state; with both on GPIO there is nothing to send
392 bool applied = true;
393 if (this->rts_pin_ == nullptr || this->dtr_pin_ == nullptr) {
394 this->with_modem_uart_([this, dtr, rts, &applied](auto *uart) {
395 applied = uart->set_modem_control(this->dtr_pin_ != nullptr ? uart->get_dtr() : dtr,
396 this->rts_pin_ != nullptr ? uart->get_rts() : rts);
397 });
398 }
399 if (!applied) {
400 ESP_LOGW(TAG, "Modem pins did not reach the UART on serial proxy [%" PRIu32 "]", this->instance_index_);
402 }
403 if (this->rts_pin_ != nullptr) {
404 this->rts_state_ = rts;
405 this->rts_pin_->digital_write(rts);
406 }
407 if (this->dtr_pin_ != nullptr) {
408 this->dtr_state_ = dtr;
409 this->dtr_pin_->digital_write(dtr);
410 }
412}
413
414#ifdef USE_API
418 this->fill_identity_(scratch, msg);
419 api_connection->send_serial_proxy_identity(msg);
420}
421
423 msg.instance = this->instance_index_;
424#ifdef USE_SERIAL_PROXY_USB_IDENTITY
425 // The define is global, so a hardware UART port in the same config also gets here
426 if (this->usb_channel_ != nullptr) {
428 // Covers a removed device, a channel the device has no CDC function for and a failed channel setup
429 auto *client = this->usb_channel_->get_parent();
430 // A device still being set up is not connected yet: its removal would not be reported
431 if (!this->usb_channel_->is_connected() || !client->is_connected()) {
432 return;
433 }
434 const uint8_t interface_number = this->usb_channel_->get_interface_number();
436 if (!client->get_device_info(scratch)) {
438 return;
439 }
440 msg.usb.vendor_id = scratch.vendor_id;
441 msg.usb.product_id = scratch.product_id;
442 msg.usb.bcd_device = scratch.bcd_device;
443 msg.usb.interface_number = interface_number;
447 msg.manufacturer = StringRef(scratch.manufacturer);
448 msg.product = StringRef(scratch.product);
449 msg.serial_number = StringRef(scratch.serial_number);
450 return;
451 }
452#endif
453 // Zero-initialized message: source NONE, no flags
454}
455#endif
456
457#ifdef USE_SERIAL_PROXY_USB_IDENTITY
459 ESP_LOGD(TAG, "USB device %s serial proxy [%" PRIu32 "]",
460 connected ? LOG_STR_LITERAL("attached to") : LOG_STR_LITERAL("removed from"), this->instance_index_);
461#ifdef USE_SERIAL_PROXY_TAP
462 // Before telling clients, so a tap never acknowledges a frame from the old device after
463 // a client has been told it is gone. The subscriber and the mode stay: both belong to
464 // the client's session, and only the client knows whether that session is over.
465 if (!connected && this->tap_ != nullptr) {
467 }
468#endif
469#ifdef USE_API
470 if (api::global_api_server == nullptr) {
471 return;
472 }
475 this->fill_identity_(scratch, msg);
477#endif
478}
479#endif
480
482 bool rts = this->rts_state_;
483 bool dtr = this->dtr_state_;
484 this->with_modem_uart_([this, &rts, &dtr](auto *uart) {
485 if (this->rts_pin_ == nullptr)
486 rts = uart->get_rts();
487 if (this->dtr_pin_ == nullptr)
488 dtr = uart->get_dtr();
489 });
490 return (rts ? static_cast<uint32_t>(SERIAL_PROXY_LINE_STATE_FLAG_RTS) : 0u) |
491 (dtr ? static_cast<uint32_t>(SERIAL_PROXY_LINE_STATE_FLAG_DTR) : 0u);
492}
493
495#ifdef USE_API
496 // Flushing stalls the port, so it gets the same ownership check as writes
497 if (!this->is_subscriber_(api_connection)) {
498 ESP_LOGW(TAG, "Ignoring flush from client without port subscription [%" PRIu32 "]", this->instance_index_);
500 }
501#endif
502 ESP_LOGV(TAG, "Flushing serial proxy [%" PRIu32 "]", this->instance_index_);
503 switch (this->flush()) {
512 }
513 return SerialProxyResult::SERIAL_PROXY_RESULT_ERROR; // Unreachable; all enum values handled above
514}
515
516#ifdef USE_API
519 switch (type) {
521 if (this->api_connection_ == api_connection) {
522 ESP_LOGV(TAG, "API connection is already subscribed to serial proxy [%" PRIu32 "]", this->instance_index_);
524 }
525 if (this->api_connection_ != nullptr) {
526 // A living subscriber keeps exclusive access. Its connection may be dead without
527 // loop() having noticed yet (e.g. the client crashed and reconnected quickly);
528 // in that case let the new client take over instead of locking it out.
529 if (this->api_connection_->is_authenticated()) {
530 ESP_LOGE(TAG, "Only one API subscription is allowed at a time");
532 }
533 ESP_LOGW(TAG, "Previous subscriber disconnected; taking over subscription");
534 // End the dead client's session before starting the new one, so its mode
535 // cannot leak into a session that never asked for it
536 this->api_connection_ = nullptr;
537 this->reset_mode_();
538 }
539 this->api_connection_ = api_connection;
540 this->enable_loop();
541 ESP_LOGV(TAG, "API connection subscribed to serial proxy [%" PRIu32 "]", this->instance_index_);
544 // Unsubscribe is idempotent: not being subscribed is not an error
545 if (this->api_connection_ != api_connection) {
546 ESP_LOGV(TAG, "API connection is not subscribed to serial proxy [%" PRIu32 "]", this->instance_index_);
548 }
549 this->api_connection_ = nullptr;
550 this->reset_mode_();
551#ifdef USE_SERIAL_PROXY_TAP
552 // Keep the loop alive for a tap that still needs the port (mirrors loop())
553 if (this->tap_ == nullptr || !this->tap_->tap_needs_port()) {
554 this->disable_loop();
555 }
556#else
557 this->disable_loop();
558#endif
559 ESP_LOGV(TAG, "API connection unsubscribed from serial proxy [%" PRIu32 "]", this->instance_index_);
561 default:
562 ESP_LOGW(TAG, "Unknown serial proxy request type: %" PRIu32, static_cast<uint32_t>(type));
564 }
565}
566#endif
567
568} // namespace esphome::serial_proxy
569
570#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:262
void disable_loop()
Disable this component's loop.
virtual void digital_write(bool value)=0
T * get_parent() const
Get the parent of this object.
Definition helpers.h:2438
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:4037
enums::SerialProxyIdentitySource source
Definition api_pb2.h:4222
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:109
optional< std::array< uint8_t, N > > read_array()
Definition uart.h:43
UARTComponent * parent_
Definition uart.h:147
void write_array(const uint8_t *data, size_t len)
Definition uart.h:30
uint8_t UARTParityOptions parity
Definition uart.h:132
uint8_t get_interface_class() const
bInterfaceClass of the interface get_interface_number() names
Definition usb_uart.h:184
uint8_t get_port_number() const
Index of this port among the ports on its interface.
Definition usb_uart.h:192
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:177
const char * get_interface_description() const
The iInterface string of the interface get_interface_number() names, read when the device connected.
Definition usb_uart.h:196
struct @67::@68 __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:362
@ SERIAL_PROXY_REQUEST_TYPE_SUBSCRIBE
Definition api_pb2.h:361
@ SERIAL_PROXY_IDENTITY_FLAG_CONNECTED
Definition api_pb2.h:389
@ SERIAL_PROXY_IDENTITY_FLAG_ERROR
Definition api_pb2.h:390
@ SERIAL_PROXY_IDENTITY_SOURCE_USB
Definition api_pb2.h:384
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
void setup_output_pin(GPIOPin *pin, bool level)
Set up pin and drive it to level. Does nothing when pin is null, so an optional pin needs no check.
Definition gpio.cpp:44
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
watchdog_hw scratch[0]